如何在 Laravel 中获取特定于用户的数据透视表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32537940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:20:05  来源:igfitidea点击:

How to get pivot data specific to user in Laravel?

phplaravellaravel-5eloquent

提问by Rob

I have a userstable, an itemstable and a pivot table item_user.

我有一张users桌子、一张items桌子和一个数据透视表item_user

I can get a list of all users items or a list of all an items users easy enough using belongsToManyrelationship.

我可以使用belongsToMany关系很容易地获得所有用户项目的列表或所有用户项目的列表。

$item->users;
$user->items;

However I'm using this as a sort of "favorites" relationship.

但是,我将其用作一种“收藏夹”关系。

So if I display ALL items on my website regardless of user, I want to know which ones the user has in the pivot table as the "favorite".

因此,如果我不考虑用户而在我的网站上显示所有项目,我想知道用户在数据透视表中将哪些项目作为“收藏夹”。

So far I have this:

到目前为止,我有这个:

// Item Model

public function favorites()
{
    return $this->belongsToMany('App\Models\User')->withPivot('user_id')->where('user_id', @\Auth::user()->id);
}

It works fine, but the query it runs is this:

它工作正常,但它运行的查询是这样的:

select `users`.*, `item_user`.`item_id` as `pivot_item_id`, `item_user`.`user_id` as `pivot_user_id` from `users` inner join `item_user` on `users`.`id` = `item_user`.`user_id` where `user_id` = '1' and `item_user`.`item_id` in ('282', '10', '826', '632', '896', '604', '8', '990', '175', '979', '7', '805', '665', '263', '507', '327', '397', '208', '762', '926', '474', '389', '433', '742', '613', '689', '782', '435', '898', '518')

I don't need the data from the userstable, I just need the pivot data:

我不需要users表中的数据,我只需要数据透视表:

SELECT user_id, item_id FROM item_user WHERE user_id = 1 AND item_id IN (1, 2, 3, 4, 5, 6, 282);

Is there anyway to run the more efficient version in Laravel?

有没有办法在 Laravel 中运行更高效的版本?

回答by Safoor Safdar

As much I understand your requirement.. it can be resolve by adding a column to pivot table.

据我了解您的要求..可以通过向数据透视表添加一列来解决。

First include 'favorite' on your pivot call to Item Model:

首先在您对项目模型的枢轴调用中包含“收藏夹”:

return $this->belongsToMany('User', 'user_items')
             ->withPivot('favorite');

Note: Vice versa can also define but didn't test that option.

注意:反之亦然也可以定义但未测试该选项。

Then to check weather it 'favorite' or not :

然后检查天气它“最喜欢”与否:

$item = User::with('items')->get()->find(1)->items->find(2)->pivot->favorite;

But in that case you also need to organise you relationship structure as user has many items. If you still any question to understand my approach please let me know.

但在这种情况下,您还需要组织您的关系结构,因为用户有很多项目。如果您对理解我的方法仍有任何疑问,请告诉我。