eloquent - Querying Laravel Relationship -


i trying 1 query work since morning , not able working have 2 tables photographers , reviews please have @ structure , ask question @ bottom :

reviews table :

id int(10) unsigned -> primary key  review text user_id int(10) unsigned foreign key users table user_name varchar(64)  photographer_id int(10) unsigned foreign key photographers table  

photographers table :

id int(10) unsigned -> primary key name text brand text description text photo text logo text featured varchar(255) 

photographers model :

class photographer extends model {  public function reviews() {     return $this->hasmany('\app\review'); } } 

reviews model :

class review extends model { public function photographers() {     return $this->belongsto('\app\photographer'); } } 

my logic query records

$response = photographer::with(['reviews' => function($q) {     $q->selectraw('max(id) id, review, user_id, user_name, photographer_id');         }])         ->where('featured', '=', 'yes')         ->get(); 

the question : want fetch photographers have @ least 1 review in review table, want fetch 1 review latest, may have more 1 review photographer want one.

i add relationship method photogrpaher class:

public function latestreview() {     return $this->hasone('app\review')->latest(); } 

then can call:

photographer::has('latestreview')->with('latestreview')->get(); 

notes:

  • the latest() method on query builder shortcut orderby('created_at', 'desc'). can override column uses passing argument - ->latest('updated_at')
  • the with method loads in latest review.
  • the has method queries photographers have @ least 1 item of specified relationship

have @ has queries in eloquent. if want customise has query further, wherehas method useful

if you're interested

you can add query methods result of relationship method. relationship objects have query builder object pass methods not exist on to, can use relationships query builder relationship.

the advantage of adding query scopes / parameters within relationship method on eloquent orm model :


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -