在laravel中组合2个表

问题描述 投票:0回答:1

我想组合我的Users Table和AcitvationCodes表,并在一个foreach循环中显示它们。我的ActivationCodes表有一个外键'user_id'。这是我的代码:

$data['codes'] = ActivationCode::orderBy('id','desc')->paginate(15);

在我的foreach循环中我添加了这个并且它不起作用。请帮忙。

 @foreach($codes as $p)
           @php $rr = \App\User::where('id',$p->user_id)->first(); @endphp
           <td>{{$rr->name}} </td>
 @endforeach
jquery database laravel
1个回答
0
投票

您正在尝试加载没有任何用户附加where('user_id', 0)的激活码。然后你试图让代码的用户User::where('id', $p->user_id)。当然,这不起作用,因为您加载的代码没有任何用户。您可以向其用户加载所有激活码:

ActivationCode::with('user')->latest('id')->paginate(15);

然后显示相关用户而不为每个用户执行新查询:

@foreach($codes as $code)
    <td>{{ $code->user->name }}</td>
@endforeach

要使其工作,您需要定义此关系:

public function user()
{
    return $this->belongsTo(User::class);
}
© www.soinside.com 2019 - 2024. All rights reserved.