查找 eloquent 型号及相关型号

Find eloquent model and related model

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

一个用户有很多目标。

我不确定该怎么做,我想该片段可能看起来像这样。

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

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

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

$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 table

$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
}