php - Laravel Eloquent hasMany\hasOne limit parents to children with records -


using laravel eloquent , hasone()\hasmany() relationship, possible limit "parent" table retrieve results if "child\foreign" relationship exists?

foos

+----+------------+ | id |     etc    | +----+------------+ |  1 |     1    | |  2 |     2    | |  3 |     3  | |  4 |     4   | +----+------------+ 

bars

+----+-----+--------+ | id | val | foo_id | +----+-----+--------+ | 11 | 101 |      1 | | 12 | 102 |      2 | | 13 | 203 |      3 | | 14 | 204 |      4 | +----+-----+--------+ 

in foo class (model)

public function highbars(){     return $this->hasone('app\bar')->where('val','>','200'); } 

in controller

foo::with('highbars')->get(); 

returns foos, though high_bars relationships null. possible include foos results relationship value not null? (foos.id = 3,4)

this retrieved...

  0 => array:3 [▼     "id" => 1     "etc" => "one"     "high_bars" => null   ]   1 => array:3 [▼     "id" => 2     "etc" => "two"     "high_bars" => null   ]   2 => array:3 [▼     "id" => 3     "etc" => "three"     "high_bars" => array:2 [▼       "id" => 13       "val" =>203       "foo_id" =>3     ]   ]   3 => array:3 [▼     "id" => 4     "etc" => "four"     "high_bars" => array:2 [▼       "id" => 14       "val" =>204       "foo_id" =>4     ]   ] 

but want..

0 => array:3 [▼     "id" => 3     "etc" => "three"     "high_bars" => array:2 [▼       "id" => 13       "val" =>203       "foo_id" =>3     ]   ]   1 => array:3 [▼     "id" => 4     "etc" => "four"     "high_bars" => array:2 [▼       "id" => 14       "val" =>204       "foo_id" =>4     ]   ] 

to quote documentation.

when accessing records model, may wish limit results based on existence of relationship. example, imagine want retrieve blog posts have @ least 1 comment. so, may pass name of relationship has method:

// retrieve posts have @ least 1 comment... $posts = app\post::has('comments')->get(); 

you may specify operator , count further customize query:

// retrieve posts have 3 or more comments... $posts = post::has('comments', '>=', 3)->get(); 

nested has statements may constructed using "dot" notation. example, may retrieve posts have @ least 1 comment , vote:

// retrieve posts have @ least 1 comment votes... $posts = post::has('comments.votes')->get(); 

if need more power, may use wherehas , orwherehas methods put "where" conditions on has queries. these methods allow add customized constraints relationship constraint, such checking content of comment:

// retrieve posts @ least 1 comment containing words foo% $posts = post::wherehas('comments', function ($query) {     $query->where('content', 'like', 'foo%'); })->get(); 

answer

for specific example, achieved using:

foo::has('highbars')->get(); 

Comments