与 Laravel 的友谊系统:多对多关系

     2023-02-16     149

关键词:

【中文标题】与 Laravel 的友谊系统:多对多关系【英文标题】:Friendship system with Laravel : Many to Many relationship 【发布时间】:2014-09-22 20:35:48 【问题描述】:

我正在尝试使用 Laravel 创建一个友谊系统(我是从它开始的),但我被人际关系所阻碍。事情是这样的:有一张表用户和一张表朋友,其中包含以下列:

friends: id, user_id, friend_id, accepted.

它看起来像多对多,所以这是我在 User 类上设置的:

class User extends Eloquent 
    function friends()
    
        return $this->belongsToMany('User');
    

但是当我尝试:

$friends = User::find($id)->friends()->get()

我有这个错误:

Base table or view not found: 1146 Table 'base.user_user' doesn't exist

我想得到一个用户的好友列表,不管用户是发送邀请还是收到邀请。因此,用户可以基于 user_id 或friend_id,然后我根据该列检索其他用户的数据。

有什么想法吗?谢谢!

编辑:这是我使用的代码:

$usersWithFriends = User::with('friendsOfMine', 'friendOf')->get();
$user = User::find(Auth::id())->friends;

foreach($user as $item) 
    echo $item->first()->pivot->accepted;
 

【问题讨论】:

foreach ($user->friends as $friend) $friend->pivot->accepted; 好的,感谢您花在上面的时间,我成功了! 我知道这是一个旧帖子,但是您如何验证好友请求?您使用自己的 Friend 模型吗? 【参考方案1】:

这显然是您的数据库中的一个问题,也是关系的定义。多对多关系类型期望您使用中间表。这是你必须做的:

    在您的架构中创建一个user_friend (id, user_id, friend_id) 表。 从userfriend 表中删除不必要的字段。 创建正确的外键。 user.id-> user_friend.user_id , friend.id -> user_friend.friend_id 更好地定义 UserFriend 模型的完整关系,

例如:

 class User extends Eloquent 
    function friends()
    
        return $this->belongsToMany('User', 'user_friend', 'user_id', 'friend_id');
    

您可以在 Laravel 文档中阅读更多内容,HERE

【讨论】:

谢谢你真的帮助我理解了多对多的工作原理。我刚从 CodeIgniter 来,有很多关于这种关系的学习(感兴趣)。但是我会接受第二个答案,你的要求多一张我在这种情况下不需要的桌子:/。 OP只有一个名为“User”的表,没有“Friend”表。 我也面临这个问题。对于多对多关系,我们需要一个中间表。但是在这种情况下,我们已经有存储用户信息的用户表,所以我们需要创建单独的朋友表。我们可以创建 user_friend 表,该表由 users 表中的 user_id 字段、friend_id 字段和 status 字段组成。它将如何与它一起工作?【参考方案2】:

tldr;您需要 2 个倒置关系才能使其工作,请检查下面的 SETUP 和 USAGE


首先是错误 - 你的关系应该是这样的:

function friends()

  return $this->belongsToMany('User', 'friends', 'user_id', 'friend_id')
    // if you want to rely on accepted field, then add this:
    ->wherePivot('accepted', '=', 1);

然后它将正常工作:

$user->friends; // collection of User models, returns the same as:
$user->friends()->get();

设置

但是您希望这种关系能够以两种方式发挥作用。 Eloquent 不提供这种关系,因此您可以改为使用 2 个倒置关系并合并结果

// friendship that I started
function friendsOfMine()

  return $this->belongsToMany('User', 'friends', 'user_id', 'friend_id')
     ->wherePivot('accepted', '=', 1) // to filter only accepted
     ->withPivot('accepted'); // or to fetch accepted value


// friendship that I was invited to 
function friendOf()

  return $this->belongsToMany('User', 'friends', 'friend_id', 'user_id')
     ->wherePivot('accepted', '=', 1)
     ->withPivot('accepted');


// accessor allowing you call $user->friends
public function getFriendsAttribute()

    if ( ! array_key_exists('friends', $this->relations)) $this->loadFriends();

    return $this->getRelation('friends');


protected function loadFriends()

    if ( ! array_key_exists('friends', $this->relations))
    
        $friends = $this->mergeFriends();

        $this->setRelation('friends', $friends);
    


protected function mergeFriends()

    return $this->friendsOfMine->merge($this->friendOf);

用法

通过这样的设置,您可以这样做:

// access all friends
$user->friends; // collection of unique User model instances

// access friends a user invited
$user->friendsOfMine; // collection

// access friends that a user was invited by
$user->friendOf; // collection

// and eager load all friends with 2 queries
$usersWithFriends = User::with('friendsOfMine', 'friendOf')->get();

// then
$users->first()->friends; // collection

// Check the accepted value:
$user->friends->first()->pivot->accepted;

【讨论】:

谢谢你的回答,我真的不知道我可以做这样的关系(合并、倒置等)。像魅力一样工作,现在我将能够在我未来的作品中使用相同类型的关系! :) 我有最后一个问题:使用 $users->friends 时,我如何知道接受的属性(我删除了 whenPivot 以选择所有朋友,无论是否接受)。 检查编辑 - 您需要 1 将 withPivot() 添加到关系中,2 您可以通过调用 friend->pivot->accepted 访问它 - 请参阅我给出的答案中的最后一个示例。 谢谢。我用我的代码编辑了我的第一篇文章,因为我无法让它工作:/。编辑:通过删除 ->wherePivot() 它可以工作,我必须保留它吗? 请告诉我们如何分页? $user->friends()->paginate(25) 将不起作用。

Laravel 与渴望的多对多关系

】Laravel与渴望的多对多关系【英文标题】:Laravelmanytomanyrelationshipwitheager【发布时间】:2021-06-0407:00:25【问题描述】:我有以下表格:-Table:facilitiesColumns:idbigint(20)UNAIPKnamevarchar(255)Table:reportsColumns:idbigint(20)UNAIPKnumbervarchar(20)visi 查看详情

与同一张表的关系(多对多?) - Laravel

】与同一张表的关系(多对多?)-Laravel【英文标题】:Relationshipwiththesametable(ManytoMany?)-Laravel【发布时间】:2019-10-1511:07:03【问题描述】:在我的数据库中,我必须保存人和第一个有关系的人的数据。例如:父亲、母亲、儿子、... 查看详情

Laravel 多对多关系检查与中间表

】Laravel多对多关系检查与中间表【英文标题】:LaravelManyToManyRelationshipCheckwithintermediatetable【发布时间】:2021-11-1205:52:53【问题描述】:我是新来的,非常希望我没有问重复的问题。我对编码完全陌生,直接进入了Laravel,但现在... 查看详情

Laravel:具有多对多关系的历史排名系统

】Laravel:具有多对多关系的历史排名系统【英文标题】:Laravel:HistoricalrankingsystemwithManyToManyrelationship【发布时间】:2016-06-1321:30:52【问题描述】:我想显示一个按排名列出用户的页面。一个排名可以有多个用户(例如,2个用户... 查看详情

Laravel 与 uuid 的多对多关系返回总是空的

】Laravel与uuid的多对多关系返回总是空的【英文标题】:Laravelmanytomanyrelationshipwithuuidreturnsalwaysempty【发布时间】:2019-10-0102:24:25【问题描述】:我使用Laravel5.8并将模型的自动增量ID更改为uuid。从那时起,我在我的两个模型Event和... 查看详情

Eloquent 中与分类学的多对多关系

...【发布时间】:2013-04-1012:09:45【问题描述】:我正在使用Laravel4。我的系统中有许多关系。我选择使用Wordpress分类表方案。但是如何使用Laravel4EloquentORM建立模型关系?这是我的数据库表;表terms:+------------+--------- 查看详情

与多个中间表的多对多 Laravel Eloquent 关系

】与多个中间表的多对多LaravelEloquent关系【英文标题】:ManytomanyLaravelEloquentrelationshipwithmultipleintermediatetables【发布时间】:2018-10-0511:41:44【问题描述】:我使用的是Laravel5.4,模型和表结构如下:users-----idaccounts--------idholdings-----... 查看详情

渴望加载 Laravel 5 与两个外键的多对多关系

】渴望加载Laravel5与两个外键的多对多关系【英文标题】:EagerLoadingLaravel5many-to-manyrelationshipwithtwoforeignkeys【发布时间】:2016-09-1806:28:55【问题描述】:在我的应用程序中,我有两个表,一个Users表和一个Forms表。Users表是带有id的... 查看详情

Laravel 多对多关系( hasMany 或 belongsToMany )

】Laravel多对多关系(hasMany或belongsToMany)【英文标题】:LaravelManytoManyRelationship(hasManyorbelongsToMany)【发布时间】:2018-01-0302:41:26【问题描述】:我目前正在使用Laravel构建我的第一个应用程序,并且偶然发现了我不知道如何设置模... 查看详情

Laravel Datatable 与多个表的多对多关系

】LaravelDatatable与多个表的多对多关系【英文标题】:LaravelDatatableManyToManyrelationshipwithmultipletables【发布时间】:2019-10-1619:19:51【问题描述】:Offer.php#modeluseApp\\OfferCategory;useApp\\OfferCountries;useApp\\OfferCreative;useApp\\OfferToo 查看详情

laravel中具有多对多关系的高级搜索

】laravel中具有多对多关系的高级搜索【英文标题】:Advancedsearchwithmanytomanyrelationshipinlaravel【发布时间】:2016-01-0119:21:40【问题描述】:我想为我的网站创建高级搜索。我的类别与书籍有多对多关系(我的主要模型)如何通过表... 查看详情

Laravel 4 多对多关系

】Laravel4多对多关系【英文标题】:Laravel4manytomanyrelationships【发布时间】:2014-02-1912:15:44【问题描述】:假设我们必须有以下表格:游戏游戏问题问题答案现在为了得到与单人游戏相关的问题,我得到了以下控制器sn-p:if($code)$g... 查看详情

Laravel中多对多关系的多重搜索子句

】Laravel中多对多关系的多重搜索子句【英文标题】:Multiplesearchclauseformany-to-manyrelationshipsinLaravel【发布时间】:2021-10-1821:13:44【问题描述】:美好的一天。我有这些东西在我的应用程序中对我来说有点问题。我有一个员工模型... 查看详情

我如何获得通过与 Laravel 5/Eloquent 的两个多对多关系关联的不同类别列表?

】我如何获得通过与Laravel5/Eloquent的两个多对多关系关联的不同类别列表?【英文标题】:HowwouldIgetadistinctlistofCategoriesassociatedthroughtwomanytomanyrelationshipswithLaravel5/Eloquent?【发布时间】:2015-08-0206:48:58【问题描述】:我有一种复杂... 查看详情

Laravel 4.1 多对多关系和条件在哪里?

】Laravel4.1多对多关系和条件在哪里?【英文标题】:Laravel4.1WhereInw/ManytoManyRelationandConditionals?【发布时间】:2014-04-1821:42:00【问题描述】:我正在开发一个应用程序,其中一部分需要使用AND搜索同一模型上的多个不同字段-又名... 查看详情

Laravel - 是不是可以与一个表和一个数据透视表建立多对多关系

】Laravel-是不是可以与一个表和一个数据透视表建立多对多关系【英文标题】:Laravel-Isitpossibletohavemany-to-manyrelationshipwithonetableandapivottableLaravel-是否可以与一个表和一个数据透视表建立多对多关系【发布时间】:2018-11-2413:39:44【... 查看详情

Laravel 4:具有额外关系的多对多

】Laravel4:具有额外关系的多对多【英文标题】:Laravel4:ManytoManywithextrarelationship【发布时间】:2013-11-1422:42:27【问题描述】:我遇到了Laravel4和“多对多”查询关系的问题。我有四张桌子:用户需要货币user_needsUser_Needs包含用户... 查看详情

Laravel 5:如何更新与多对多相关的项目(删除+添加)

】Laravel5:如何更新与多对多相关的项目(删除+添加)【英文标题】:Laravel5:howtoupdateitems(remove+add)inrelationmanytomany【发布时间】:2021-08-2417:26:55【问题描述】:我使用的是Laravel5。有一个多对多的关系classVisitextendsModelpublicfunctionv... 查看详情