Mar*_*gen 1 foreign-keys relational-database laravel eloquent
我有 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 = [
'gender', 'first_name','last_name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
...
public function company()
{
return $this->belongsTo(Company::class,'company_id');
}
}
Run Code Online (Sandbox Code Playgroud)
<?php
namespace App;
use App\Events\GeneralEvent;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Nicolaslopezj\Searchable\SearchableTrait;
class Company extends Model
{
use SoftDeletes, SearchableTrait;
...
public function branche()
{
return $this->belongsTo(Branche::class);
}
}
Run Code Online (Sandbox Code Playgroud)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Nicolaslopezj\Searchable\SearchableTrait;
class Branche extends Model
{
protected $fillable = [
'name'
];
protected $searchable = [
'columns' => [
'name' => 10,
],
];
public function companies()
{
return $this->hasMany(Company::class);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我转储 $user->company 时,我得到了空值。因此,在此之后添加分支现在毫无意义。当我转储用户时,关系出现但为空。我不知道我哪里出错了。有人可以帮忙吗?
您必须包含分支机构的 id,以便 eloquent 可以链接分支机构和公司,您可以这样做
$users = User::with(['company','company.branche' => function($q){
$q->select('id','name');
}])->inRandomOrder()->paginate(24);
Run Code Online (Sandbox Code Playgroud)
或者像那样
$users = User::with(['company','company.branche' => function($q){
$q->select('id','name');
}])->inRandomOrder()->paginate(24);
Run Code Online (Sandbox Code Playgroud)