1

我在将子关系从 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');
}

我想做的是:在用户模型中,我想急切地加载该用户的所有卡片。所以我的代码如下所示:

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

我做错了什么伙计们?

4

1 回答 1

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();
于 2018-07-14T21:53:56.687 回答