【问题标题】:Eloquent nesting with clause in the middle relation中间关系中带有子句的雄辩嵌套
【发布时间】:2014-09-23 19:43:56
【问题描述】:

我有以下关系:

  • 用户 [many-to-many with] 分配
  • 作业 [多对多与] 徽章
  • assignment_user 数据透视表有一个标志“is_finished”,我需要设置为 true

这些是我在匹配模型中的关系:

用户.php

public function assignments()
{
return $this->belongsToMany('Assignment')->withPivot('is_finished')->withTimestamps();
}

assignment.php

public function badges()
{
return $this->belongsToMany('Badge', 'badge_assignment')->withTimestamps();
}

徽章.php

public function assignments()
{
return $this->belongsToMany('Assignment', 'badge_assignment')->withTimestamps();
}

我正在尝试为我的用户完成的作业获取所有徽章。这是我的查询:

$user = User::with(array(
'assignments' => function($query) {
$query->where('is_finished', '=', true)->orderBy('updated_at', 'desc');
})
)
->with('badges')
->username($name)->first();

但是,当我使用 foreach($user->assignments->badges ...) 时,这会呈现错误“调用未定义的方法 Illuminate\Database\Query\Builder::badges()”。

然后我尝试在第一个范围内获取徽章,但我不知道如何到达 is_finished:

$user = User::with(array(
'assignments.badges' => function($query) {
$query->where('is_finished', '=', true)->orderBy('updated_at', 'desc');
})
)
->username($name)->first();

这样我得到“找不到列”,因为查询是在徽章中寻找 is_finished,而不是 assignment_user 关系。

当我遇到这个问题时,我尝试了这个只是为了确定:

User::with('assignments.badges')->whereUsername($username);

...我仍然收到“未定义的属性:Illuminate\Database\Eloquent\Collection::$badges”。

我做错了什么?

【问题讨论】:

    标签: laravel eloquent nested


    【解决方案1】:

    你需要像这样加载嵌套的assignments.badges

    $user = User::with(array(
        'assignments' => function($query) {
          $query->where('is_finished', '=', true)->orderBy('updated_at', 'desc');
        })
      )
      ->with('assignments.badges')
      ->username($name) // do you have a scope for this or should it be whereUsername?
      ->first();
    

    【讨论】:

    • 使用您的代码会呈现与我的第三次(简单)尝试相同的错误:“未定义的属性:Illuminate\Database\Eloquent\Collection::$badges”。仅供参考,从查询中获取结果后,我在视图中使用 $user->assignments->badges。
    • 我不这么认为。您可能正在尝试这样调用:$user->assignments->badges,它显然会抛出此错误。对于急切加载本身,我的代码是要走的路,相信我。好吧,是的,你当然不能这样做 - 你想在模型的 collection 上获取 model's 关系 - 例如,你需要一个 foreach 循环。
    • 傻我,你当然是对的。我很愚蠢,试图在不为每个作业运行第二个循环的情况下获取徽章。非常感谢您的快速解决方案!
    • 只是出于好奇,这对于 3 级深度嵌套如何工作?我不能只使用 with('table1.table2.table3') - 它是如何工作的?
    • 您可以随意使用点嵌套关系,所以是的,relation1.relation2.relation3 .... 可以工作(不是 table1 等,而是模型中的关系名称)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2019-06-22
    • 2017-10-18
    • 2020-05-10
    • 2021-05-29
    • 1970-01-01
    • 2020-09-29
    相关资源
    最近更新 更多