我有下表结构
Users table
id- integer
name-string
Casefiles table
id- integer
user_id- foreign_key
name-string
Followups table
id- integer
date- date
casefile_id-foreign_key
我在这个模型User.php之间使用以下关系
public function casefiles()
{
if ($this->hasRole(['sales_executive'])) {
return Casefile::where('user_id', $this->id);
}
}
Casefile.php
public function user()
{
return $this->belongsTo('App\User');
}
public function followups()
{
return $this->hasMany('App\FollowUp');
}
Followup.php
public function casefile()
{
return $this->belongsTo('App\Casefile');
}
我想直接获取用户跟进。我怎样才能实现这一目标?
你需要在你的hasManyThrough()
中使用User.php
你可以添加这个,
public function followUps()
{
return $this->hasManyThrough('App\FollowUp','App\Casefile');
}
那么你通常可以使用User::with('followUps')->find(1)->followUps
调用后续内容
我注意到你正在检查你的关系中的角色$this->hasRole(['sales_executive']
这可能会发生错误,因为如果声明是假的你不是。我认为你接受另一个接近并处理它。有关hasManyThrough的更多信息,请更喜欢这个link
这应该是HasManyThrough关系的情况。
在你的情况下它应该是
// Followups migration
Schema::create('followups', function (Blueprint $table) {
$table->bigIncrements('id');
$table->date('date');
$table->unsignedBigInteger('casefile_id')->nullable();
$table->timestamps();
$table->foreign('casefile_id')
->references('id')
->on('casefiles');
});
// Casefile migration
Schema::create('casefiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users');
});
// User.php
public function followups() {
return $this->hasManyThrough(FollowUp::class, Casefile::class);
}
// YourController.php
$user = User::all()->first();
dd($user->followups);
更改模型User.php以获取与casefiles和followups的关系:
public function casefiles()
{
if ($this->hasRole(['sales_executive'])) {
return $this->hasMany(Casefile::class);
}
}
public function followups() {
return $this->hasManyThrough(FollowUp::class, Casefile::class);
}