【问题标题】:Laravel 5.6 eager load nested childrelationsLaravel 5.6 急切加载嵌套的子关系
【发布时间】:2018-07-14 21:45:28
【问题描述】:

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

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

所以反过来说:

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

我的卡片模型有这个:

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

我想要做的是:在 User 模型中,我想预先加载该用户的所有卡片。所以我的代码如下所示:

$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');
    });

我做错了什么?

【问题讨论】:

  • Card::with('company.user')->get() 如何知道登录的用户?你不是说像Auth::user()->load('company.cards')这样的东西吗?

标签: laravel loading laravel-5.6 eager


【解决方案1】:

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();

【讨论】:

  • 这就是您使用$with 数组的地方。
  • 用另一种方法更新。
  • whereHas 和 whereKey 的最后一件事!谢谢
猜你喜欢
  • 1970-01-01
  • 2014-12-28
  • 2015-08-16
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
  • 2017-03-01
  • 2012-12-11
相关资源
最近更新 更多