【发布时间】:2018-03-01 00:17:32
【问题描述】:
问题
我为我的 Laravel 应用创建了一个简单的友谊关系,一切正常,直到我注意到当我查询用户的友谊时,它只会在 UID1 字段上搜索当前用户。
由于友谊本质上是一种双向关系,我试图在 laravel 模型中找到一种方法来通过多个列检索所有友谊关系。
当前实施
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 |
+----------------------+
根据下面朋友表中的数据,如果 Current UserID = 1,当前的实现只会返回其中 1 条记录。
+-------------------------------+
| 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
更新
我创建了一个 FriendShip 帮助器类,它做类似的事情,但是在这个函数中我明确地传入了 UserID
Friendship::where( [
[ 'uid1' ,'=', $uid],
])->orWhere( [
[ 'uid2', '=', $uid]
])->all();
【问题讨论】:
标签: php mysql laravel laravel-5