A
A
Alexey Merzlyakov2018-01-31 20:28:24
Laravel
Alexey Merzlyakov, 2018-01-31 20:28:24

Relationships of 3 tables in Laravel?

It is necessary to display articles created by users, on which users are subscribed by the user.
There are 3 tables
Users - id fields
Posts - id fields, user_id
Subscriptions - id fields, user_id (user), user_sub_id (who is subscribed to, one value)
Models

class User extends EloquentUser{
     public function postsSub(){
        return $this->hasManyThrough('App\Post', 'App\Subscription', 'user_id', 'user_id');
    }
}

In the controller I do the following I receive a request
$posts = User::find(1)->postsSub()->toSql();
select * from `posts` inner join `subscriptions` on `subscriptions`.`id` = `posts`.`user_id` where `subscriptions`.`user_id` = 1

I need the request to have `subscriptions`.` user_sub_id ` = `posts`.`user_id` instead of `subscriptions`.` id ` = `posts`.` user_id ` Actually, how can such a request be formed
select * from `posts` inner join `subscriptions` on `subscriptions`.`user_sub_id` = `posts`.`user_id` where `subscriptions`.`user_id` = 1

Or, how else can it be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SteepZero, 2018-02-07
@SteepZero

Use belongsToMany

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question