Laravel 5.5用户模型和朋友关系(属于ToMany)(按多列) [英] Laravel 5.5 User model and friends relationship (belongsToMany) by multiple columns

查看:83
本文介绍了Laravel 5.5用户模型和朋友关系(属于ToMany)(按多列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为Laravel应用程序创建了一个简单的友谊关系,所有这些关系都正常运行,直到我注意到查询用户的友谊时,它只会在UID1字段中搜索当前用户.

I created a simple friendship relationship for my Laravel app which all worked ok until I noticed that when I queried the friendship of a user it would only search the current user on the UID1 field.

由于友谊本质上是一种双向关系,因此我试图在laravel模型中找到一种方法以通过多列检索所有友谊关系.

Since friendships are in essence a two-way relationship, Im trying to find a way in a laravel Model to retrieve ALL friendships relations by multiple columns.

    public function friends()
    {
        return $this->belongsToMany( App\Modules\Users\Models\User::class ,'friends', 'uid1');
    }

理想的实现方式

    public function friends()
    {
        $a = $this->belongsToMany( App\Modules\Users\Models\User::class ,'users_friends', 'uid1');
        $b = $this->belongsToMany( App\Modules\Users\Models\User::class ,'users_friends', 'uid2');

        return combine($a,$b);

    }

表结构

     +----------------------+
     | users table          |
     +----------------------+
+----|   id: primary UserID |
|    |   fname: string      |
|    +----------------------+
|    
|    
|    +----------------------+
|    | friends table        |
|    +----------------------+
|    |   id: primary iD     |
|    |                      |
+----|   uid1: user_id      |
|    |                      |
+----|   uid2: user_id      |
     +----------------------+

根据下面的好友表中的数据,如果当前用户ID = 1,则当前实现只会返回这些记录中的1条.

The current implementation will only result in 1 of these records returning if the Current UserID = 1 as per the data in the friends table below.

     +-------------------------------+
     |      friends table (data)     |
     +--------|---------|------------+
     |   id   |  uid1   |   uid2     |
     +--------|---------|------------+
     |    1   |   1     |    7       |
     |    2   |   7     |    1       |
     |    3   |   9     |    1       |
     +-------------------------------+      

用户模型

<?php

namespace App\Modules\Users\Models;

use Illuminate\Database\Eloquent\Model;


class User extends Model
{


    protected $table = 'users';


    protected $fillable = [
        'username', 'email', 'password', .... . 
    ];


    public function friends()
    {
        return $this->belongsToMany( App\Modules\Users\Models\User::class ,'users_friends', 'uid1');

    }

环境

  • 服务器= Homestead/linux
  • PHP = 7
  • MySQL
  • Environment

    • Server = Homestead/linux
    • PHP = 7
    • MySQL
    • 我有一个创建的FriendShip辅助类,它执行类似的操作,但是在此函数中,我明确地传递了UserID

      I have a FriendShip helper class I created which does something similar, however in this function I pass in the UserID explicitly

      Friendship::where( [
                          [ 'uid1' ,'=', $uid],
                      ])->orWhere( [
                          [ 'uid2', '=', $uid]
                      ])->all();
      

      推荐答案

      在声明关系时,可以通过简单地链接它来添加其他条件.

      You can add additional conditions when you're declaring relationship by simply chaining it.

      <?php
      //...
      class User extends Model {
      //...
          public function friends() {
              return $this->hasMany(/*...*/)->orWhere('uid2', $this->id);
          }
      //...
      

      但是请记住,雄辩并没有将括号中的关系的第一个条件分组,因此您可能会以在某些情况下无法正常工作的SQL结尾(如果使用应该可以)

      But keep in mind that eloquent is not grouping the first conditions of relation in parenthesis so you might end with SQL that will not work as expected in some cases (if using or, and should be fine)

      例如,上面的代码可能会导致如下所示的SQL

      For example the above might result in a SQL that looks like this

      SELECT * FROM users_friends WHERE uid1 = ? AND uid1 IS NOT NULL OR uid2 = ?
      

      这是正确的SQL语句,但是如果不进行分组,将无法获得预期的结果.

      Which is a correct SQL statement but without grouping you will not get the result that you're expecting.

      另一种方法是使用访问器和两个单独的关系

      Another way is to use accessor and two separate relationships

      <?php
      //...
      public function friends1() {
          return $this->belongsToMany(User::class, 'users_friends', 'uid1');
      }
      
      public function friends2() {
          return $this->belongsToMany(User::class, 'users_friends', 'uid2');
      }
      
      public function getFriendsAttribute() {
          return $this->friends1->merge($this->friends2);
      }
      //...
      

      但是,这样一来,您将获得两次单独的DB旅行.

      But this way you get two separate trips to DB.

      这篇关于Laravel 5.5用户模型和朋友关系(属于ToMany)(按多列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆