根据 Laravel 中 for 循环中的其他对象获取对象

Get object depending on other object within for-loop in Laravel

我有这个简单的 Laravel 应用程序,其中第一个页面 table 来自数据库。

像这样:

  @foreach ($cases in $case)
    {{ $case->title }}
    {{ $case->description }}
  @endforeach

只有一件事我无法开始工作。每个案例都归一个用户所有,因此我的数据库 table 'Cases' 包含一个名为 'owner_id' 的列。我想显示拥有 'Case' 对象的 'User' 的属性。

我读到在 'view' 中写这种编码并不整洁。但是我不知道如何在控制器 class 中做这样的事情,因为我的方法是在 for-loop

中做

在我尝试合并这两个对象之前,我可以访问用户和案例对象的属性

$cases = DB::table('cases')->get();

    $userCases = array();

    for ($i=0; $i < count($cases); $i++) {
        $case = $cases[$i];

        $user = DB::table('users')->where('id', $case->owner_id)->first();

        array_push($userCases, array($case, $user);
     }

但这似乎不起作用,因为数组只填充了指针。

使用 belongsTo-relationship.

在您的 Case-模型中,添加以下方法:

app/models/UserCase.php:
<?php 
class UserCase extends \Eloquent // "Case" is reserved in PHP, so we use a custom name
{
    protected $table = 'cases';
    //....
    public function user() // you could call it owner or whatever
    {
        return $this->belongsTo('User', 'owner_id');    

    }
}

现在,在获取案例时,不要使用直接查询,而是:$cases = UserCase::all()。出于性能原因,您会希望加载 User 模型,这样您就不会在循环中每次访问用户信息时都查询数据库。所以实际负载:$cases = UserCase::with('user')->get();

现在,要获取有关案例所属用户的信息,您只需执行 $case->user->firstname 或任何您的列名即可。所以,在你原来的 blade-example 的基础上,你会做这样的事情:

   @foreach ($cases in $case)
        {{ $case->user->firstname }}
        {{ $case->title }}
        {{ $case->description }}
    @endforeach