Laravel 4 Eloquent Query Builder - Complicated joins with variable -
i'm trying replicate join using laravel query builder:
left join content_userdata on content_id = content.id , user_id = $user_id
i have discovered can additional "ons" using following function in model extends eloquent
public function scopejoinuserdata($query, $user_id) { return $query->leftjoin('content_userdata', function($join) { $join->on('content_userdata_content_id', '=', 'content.content_id')->on('content_userdata_user_id', '=', 10); }); }
but creates 2 problems. firstly cannot $user_id variable function , secondly if hardcode testing purposes have done above (to int "10") laravel encases in ` meaning interpreted column name when shouldn't be, so:
left join `content_userdata` on `content_id` = `content`.`id` , `user_id` = `10`
so have 2 problems.
- i cannot $user_id join function when using query scopes
- even if cannot send variable join since interprets column name
why want this? realise 1 response may place in where. trying way join may not return results (hence left join), since content_userdata table contains things users rating piece of content. if use results nothing in content_userdata table not returned, if can put in join returned due left join.
is there anyway achieve in laravel , if not alternatives, changing ditching laravel on top alternative can think of userdata in separate query.
you need pass variable closure using use
keyword - imports variable scope. example:
public function scopejoinuserdata($query, $user_id) { return $query->leftjoin('content_userdata', function($join) use ($user_id) { $join->on('content_userdata_content_id', '=', 'content.content_id') ->on('content_userdata_user_id', '=', db::raw($user_id)); }); }
this php syntax related issue , not laravel limitation!
Comments
Post a Comment