Laravel 5.6渴望加载嵌套子关系

时间:2018-07-14 21:45:29

标签: laravel loading laravel-5.6 eager

我在将子关系从Card对象转换为User对象时遇到问题。关系如下:

'User' -> hasOne 'Company' 
'Company' -> hasMany 'Card'

另一种方法是:

'Card' -> belongsTo 'Company' 
'Company' -> belongsTo 'User'

我的Card模型具有此功能:

public function company()
{
    return $this->belongsTo('App\Company');
}

“我的公司”模型具有此功能:

public function user()
{
    return $this->belongsTo('App\User');
}

public function cards()
{
    return $this->hasMany('App\Card');
}

我的用户模型具有此功能:

public function company()
{
    return $this->hasOne('App\Company');
}

我想做的是:在用户模型中,我希望从该用户加载所有卡。所以我的代码如下:

$cards = Card::with('company.user')->get();

但是它不断向我返回数据库中的所有卡记录,而不是来自已登录用户本身的记录。肯定有 是一个用户ID,因为当我在用户模型中转储$ this-> id时,我得到的ID为“ 1”。在数据库中,我已经配置了所有外键,所以这不会是我假设的问题。

表“ cards”的外键为“ company_id”,表“ companies”的外键为“ user_id”,它们均由迁移脚本设置,如下所示:

Schema::create('cards', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('amount');
        $table->string('status');
        $table->unsignedInteger('company_id');
        $table->timestamp('expires_at')->nullable();
        $table->boolean('is_debit_allowed')->default(1);
        $table->string('cancelled_by')->nullable();
        $table->timestamp('cancelled_at')->nullable();
        $table->timestamps();
        $table->foreign('company_id')->references('id')->on('companies');
    });

我在做什么错人?

1 个答案:

答案 0 :(得分:0)

User模型中,您可以将其添加到$with数组中:

// this will eager load the company and cards for every user query, so beware!
protected $with = ['company.cards'];

或创建一个新功能cards

public function cards()
{
    return $this->company->cards;
}

$cards = $user->cards();

// use the auth helper to get logged in user's cards
$cards = auth()->user()->cards();

这应该可以通过Card进行访问:

$cards = Card::whereHas('company.user', function ($query) {
    $query->whereKey(auth()->id());
})->get();
相关问题