【问题标题】:Search with relations eloquent搜索关系雄辩
【发布时间】:2018-07-26 03:45:32
【问题描述】:

我想通过

后面的 ($_POST['search'] '"name" and "lastname"') 搜索用户

"用户 ID = 1"

我得到了表用户,在用户中我得到了

“姓名”和“姓氏”

我得到了表追随者,我得到了追随者

“follower_id”和“user_id”...

我知道要做到这一点,我必须使用相关的模型,但我不知道如何......

//$user_id = 1 (in followers.user_id)
//$_POST['search'] (in users.name and users.lastname)

public function u_followers_search($user_id) {

$followers = ...

return $followers;

}

【问题讨论】:

  • 看看这个article
  • 你们已经有关系了吗?

标签: laravel eloquent


【解决方案1】:

您需要在 User 模型上建立关系:

function followers() {
    return $this->hasMany(Follower::class)
}

这将使您能够做到:

$userId = 1 // or however you get the user id
$user = User::findOrFail($userId)->followers;

编辑:

有了这种关系,这意味着您将能够获得关注特定用户的所有关注者:

$allFollowers = User::findOrFail($userId)->followers;

这将为您提供所有关注 ID 为 1 的用户的用户

然后您可以继续查询并添加匹配条件

$allFollowers->where('name', 'like', '%' . $search . '%')
             ->orWhere('lastname', 'like', '%' . $search . '%')
             ->get();

这将过滤 ID 为 1 的用户的所有关注者,并仅获取在其 namelastname 中具有搜索查询的关注者

编辑 2:

要使上述方法起作用,您需要以两种方式建立关系:

User模特:

function followers() {
    return $this->hasMany(Follower::class)
}

Follower型号:

function user() {
    return $this->belongsTo(User::class)
}

这将使您能够获得指定用户的关注者

【讨论】:

  • 但是我想用$_POST['search']按姓名和姓氏搜索,ID是被关注的用户的ID...
  • 为了清楚起见,您想搜索与namelastname 匹配的User 并获得他们的关注者?
  • @ValterSousaCardoso 是您想要实现的编辑吗?
  • 此行将只获取用户 1 的关注者:$allFollowers = User::findOrFail($userId)->followers; 然后您可以使用后面的查询细化该列表以仅获取与搜索查询匹配的关注者
猜你喜欢
  • 1970-01-01
  • 2017-06-28
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2019-07-30
  • 2021-12-15
相关资源
最近更新 更多