我在将子关系从 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');
});
我做错了什么伙计们?