Laravel 用户朋友的搜索查询
Laravel search query for user's friends
我对查找特定用户朋友的搜索查询感到困惑。
我为朋友关系创建了一个支点table。
朋友Table
id
sender
recipient
用户table
id
name
email
password
etc...
请指导特定用户的朋友搜索查询应该是什么。
如果您设置了模型,那么它很简单:
User::friends();
friends()函数描述了本例中User模型和Friend模型之间的关系。
User 模型示例 belongsToMany 函数中的第二个参数是枢轴 table name:
class User extends Model
{
public function friends()
{
return $this->belongsToMany("App\Friend", "user_friend");
}
}
好友模型示例(可用于逆向查询)。
class Friend extends Model
{
public function friends()
{
return $this->belongsToMany("App\User", "user_friend");
}
}
您需要声明与自身的多对多关系
class User extends Model
{
public function friends()
{
return $this->belongsToMany(self::class, 'friends', 'sender', 'recipient');
}
}
并使用它
$friends = User::find(3)->friends;
或者过滤叫Jon的好友
$friends = User::find(3)->friends()->where('name', 'Jon')->get();
我对查找特定用户朋友的搜索查询感到困惑。
我为朋友关系创建了一个支点table。
朋友Table
id
sender
recipient
用户table
id
name
email
password
etc...
请指导特定用户的朋友搜索查询应该是什么。
如果您设置了模型,那么它很简单:
User::friends();
friends()函数描述了本例中User模型和Friend模型之间的关系。
User 模型示例 belongsToMany 函数中的第二个参数是枢轴 table name:
class User extends Model
{
public function friends()
{
return $this->belongsToMany("App\Friend", "user_friend");
}
}
好友模型示例(可用于逆向查询)。
class Friend extends Model
{
public function friends()
{
return $this->belongsToMany("App\User", "user_friend");
}
}
您需要声明与自身的多对多关系
class User extends Model
{
public function friends()
{
return $this->belongsToMany(self::class, 'friends', 'sender', 'recipient');
}
}
并使用它
$friends = User::find(3)->friends;
或者过滤叫Jon的好友
$friends = User::find(3)->friends()->where('name', 'Jon')->get();