【发布时间】: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