php - Making a join with Eloquent based on a list of ids -
i have set 2 eloquent models belongstomany
relation in both directions. works fine need make more detailed query within relationship. keep things simple, let's tables have following columns:
wigs: - id - name - type heads: - id - name heads_wigs: - head_id - wig_id
now need fetch series of wigs
given type
within list of given head
id
's. have is:
- a
wig
type
- an array
head
id
's
i using eloquent outside of laravel want start building orm query on model. like:
wig::where( 'type', $type )-> ... //here code make join on head id's
this understanding of sql lacks suppose should not hard achieve.
update:
to rephrase in sentence: get wigs type=wig_type have belongstomany relationship heads [1,2,3,5,6,8,9]
. want end collection of wigs
performing single query.
you this
head::wherein('id', $head_id_array)->load(['wig' => function($query) use ($wig_type) { $query->where('type', $wig_type); }])->get();
or
wig::where('type', $wig_type)->load(['heads' => function($query) use ($head_id_array) { $query->wherein('id', $head_id_array); }])->get();
if understand question correctly.
or
$wig = wig::where('type', $wig_type)->get(); $heads = $wig->heads()->wherein('id', $head_id_array)->get(); $matching_head_ids = $heads->lists('id'); $wig->matching_head_ids = $matching_head_ids;
that way, wig object returned have array of matching head ids.
you put in method on wig model:
class wig extends eloquent { public function heads() { return $this->belongstomany('head'); } /** * @param array $head_ids provided head id array * @return array array of wigs head id's match provided head ids */ public function matchingheadids($head_ids) { return $this->heads()->wherein('id', $head_ids)->get()->lists('id'); } }
then use so
$wig = wig::where('type', $wig_type); $wig->matchingheadids($head_ids);
edit
this not simple task orm eloquent, since treats each record row table, wouldn't work:
$wigs = head::wherein('id', $head_ids)->wigs()->where('type', $wig_type)->get();
there wherehas method available can use so:
wig::where('type', $wig_type)->wherehas('heads', function ($query) use ($head_ids) { $query->wherein('id', $head_ids); })->get();
which should give results need.
Comments
Post a Comment