laravel one-to-many 关系为空

laravel one-to-many relationship is null

我有 3 个模型:用户、公司和分支机构。

在 blade 文件中,我希望能够显示用户公司所属的分支机构。

在我看来我应该有以下关系:

用户->公司:用户属于一个公司,一个公司有很多用户,所以这是一个one-to-many关系。

公司->分公司:一个公司属于一个分公司,一个分公司可以有多个公司。所以再次one-to-many关系。

我在用户 table 中有外键:company_id 引用了公司 table 的 ID。 公司 table 中的另一个 FK:branch_id 引用了分支 table.

上的 id

在我的 blade 文件中,想要显示这样的分支名称:{{ $user->company->branch->name }} 其中只有名称是 属性。公司和分公司是关系。

我的查询如下所示:

 $users = User::with(['company','company.branche' => function($q){
            $q->select('name');
        }])->inRandomOrder()->paginate(24);
<?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');
    }   

}
<?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);
    }   
}
<?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);
    }
}

然而,当我转储 $user->company 时,我得到 null。所以在那之后添加分支现在是没有意义的。当我转储用户时,关系显示但为空。我不知道我哪里出错了。有人可以帮忙吗?

您必须包含分支机构的 ID,以便 eloquent 可以 link 分支机构和公司 你可以这样做

 $users = User::with(['company','company.branche' => function($q){
            $q->select('id','name');
        }])->inRandomOrder()->paginate(24);

或者像那样

 $users = User::with('company.branche:id,name')->inRandomOrder()->paginate(24);

所以问题是我的外键之一指向错误 table。呵呵