php - How to return model rows where id is equal to id on other table with relations in laravel? -
for example have:
// returns projects $projects = projects::all();
to return categories, belonging project, use relationships , can like:
foreach($projects $project) { ...show $project->categories... }
i need specific projects, followed specific user. on projects_followers
table have user_id
, project_id
.
to retrieve projects followed have peace of code:
$projects = project::rightjoin(db::raw('(select * projects_followers group project_id) projects_followers'),'projects_followers.project_id','=','projects.id')->get(); // note: code doesn't include specifuc user_id.
it retrieve specific rows, problem code laravel relationhips dont work on them. example $project->categories
return empty.
// relationship public function categories() { return $this->belongstomany('app\category'); }
how retrieve model specific rows , make relationships work?
actually question is:
how projects liked/followed auth/logged in user ?
unfortunately described in such way looks else, anyways. lets try find solution , use this:
$projects = auth::user()->favorite_projects;
so how can implement work, first of user model
should contain method favoriteprojects
lets create it:
public function favoriteprojects() { return $this->belongstomany( 'app\project', 'projects_followers', // table exists mentioned 'user_id', 'project_id' ); }
that's it. able load projects followed current user , other relationship methods work on every single project well.
Comments
Post a Comment