Answer the question
In order to leave comments, you need to log in
Relationships between tables (models) in Laravel?
There are 3 tables: Articles, Article_categories, User_categories.
$res = User::with(array('categories' => function($query)
{
$query->with('categoryAnn.announcements');
}))->where("id", 1)->get();
public function categories()
{
return $this->hasMany('App\CategoryUser', "user_id", "id");
}
public function categoryAnn()
{
return $this->hasMany("App\AnnouncementCategory", "category_id", "category_id");
}
public function announcements()
{
return $this->belongsTo("App\Announcement", "announcement_id", "id");
}
CREATE TABLE Announcements
(`id` int, `name` varchar(7))
;
CREATE TABLE Categories_announcements
(`announcement_id` int, `category_id` int)
;
CREATE TABLE Categories_user
(`category_id` int, `user_id` int)
;
INSERT INTO Announcements
(`id`, `name`)
VALUES
(1, 'OpenIDM'),
(2, 'OpenAM'),
(3, 'OpenDJ')
;
INSERT INTO Categories_announcements
(`announcement_id`, `category_id`)
VALUES
(1, 1)
;
INSERT INTO Categories_user
(`category_id`, `user_id`)
VALUES
(1, 1)
;
Answer the question
In order to leave comments, you need to log in
Set the user's hasMany link to the user's categories, and set the category's hasMany link to articles. And then do User::with('categories' => function($query) {$query->with('articles')}) and parse the resulting array
And doesn't that work?
User::with(
['categories', 'categoryAnn', 'categoryAnn.announcements']
)->find($userId);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question