我有 3 个模型:用户、公司和分支。
在刀片文件中,我希望能够显示用户公司所属的分支。
在我看来,我应该有以下关系:
User -> Company :用户属于一个公司,一个公司有很多用户,所以这是一对多的关系。
公司->分公司:一个公司属于一个分公司,一个分公司可以有多个公司。于是又是一对多的关系。
我在用户表中有外键: company_id 引用公司表上的 id 。公司表中的另一个 FK: branch_id 引用了分支表上的 id。
在我的刀片文件中,想要显示这样的分支名称:{{ $user->company->branch->name }} 其中只有 name 是一个属性。公司和分公司是关系。
我的查询如下所示:
$users = User::with(['company','company.branche' => function($q){
$q->select('name');
}])->inRandomOrder()->paginate(24);
Run Code Online (Sandbox Code Playgroud)
<?php
namespace App;
use App\Events\GeneralEvent;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Nicolaslopezj\Searchable\SearchableTrait;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, SoftDeletes, HasRoles, SearchableTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = …Run Code Online (Sandbox Code Playgroud)