J
J
junart2017-02-26 14:41:10
Laravel
junart, 2017-02-26 14:41:10

Relationships between tables (models) in Laravel?

There are 3 tables: Articles, Article_categories, User_categories.

  1. Each article can belong to one or more categories.
  2. Each user can be subscribed to one or more categories.
  3. The Users table is not linked to the Articles table.

I need to display all articles to which the user is subscribed by category.
All my attempts to build relationships between models were unsuccessful.
Leaning towards Has-Many-Through, which didn't work either.
Detailed question asked on stack: stackoverflow.com/questions/42458971/how-to-rewrit...
In the end, what I got:
$res = User::with(array('categories' => function($query)
        {
            $query->with('categoryAnn.announcements');
      
        }))->where("id", 1)->get();

Model user:
public function categories()
    {
        return $this->hasMany('App\CategoryUser', "user_id", "id");
    }

ModelCategoryUser:
public function categoryAnn()
    {
        return $this->hasMany("App\AnnouncementCategory", "category_id", "category_id");
    }

Model AnnouncementCategory:
public function announcements()
    {
        return $this->belongsTo("App\Announcement", "announcement_id", "id");
    }

It looks like it works. BUT!
How to get to the final Announcement without writing 5 nested loops?! I mean, you need to go through the User collection, then inside the categories , then the CategoryUser , then the categoryAnn and finally the announcements . This is some kind of pi ** c ...
Table structure:
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)
;

sqlfiddle.com/#!9/ec162/3

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Evgrafovich, 2017-02-26
@Tantacula

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

V
Vyacheslav Plisko, 2017-02-27
@AmdY

And doesn't that work?

User::with(
    ['categories', 'categoryAnn', 'categoryAnn.announcements']
)->find($userId);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question