【问题标题】:Find eloquent model and related model查找 eloquent 模型和相关模型
【发布时间】:2020-12-20 15:55:09
【问题描述】:

我需要通过 id 找到用户的目标。

一个用户有很多目标。

我不知道该怎么做,我想 sn-p 可能看起来像这样。

$goal = User::find($userId)->goals()->find($id);

是否可以同时获取相关模型并在父模型上进行过滤?

【问题讨论】:

  • 当你已经有了goal的$id——假设$id对应goals表的主键,为什么还要经过User模型。使用主键$goal = Goal::findOrFail($id);可以直接获取进球记录
  • 我想确保目标属于用户
  • 策略应该用于授权,而不是在查询上附加位! laravel.com/docs/8.x/authorization#creating-policies

标签: php laravel eloquent model


【解决方案1】:

您可以通过在预先加载关系时使用约束来限制相关记录,然后获取第一个

$goal = User::with(['goals' => fn($query) => $query->where('goals.id', $id)])
    ->findOrFail($userId)
    ->goals
    ->first();

//Then check whether a goal is present as per the constraint before proceeding further

if($goal) {
    //Do something
}

另一种选择是通过goals

$goal = Goal::with('users')->findOrFail($id);

if($goal->users->contains('id', $userId) {
    echo "User with an id of {$userId} has the given goal";

    //Do something
}

【讨论】:

  • 完美,正是我想要的!
猜你喜欢
  • 2018-04-20
  • 2013-05-25
  • 1970-01-01
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多