我具有以下表格结构
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');
}
我想直接获取用户跟进信息。我怎样才能做到这一点?
答案 0 :(得分:0)
您需要在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
答案 1 :(得分:0)
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);
答案 2 :(得分:-1)
更改User.php模型中与casefile和后续文件的关系:
public function casefiles()
{
if ($this->hasRole(['sales_executive'])) {
return $this->hasMany(Casefile::class);
}
}
public function followups() {
return $this->hasManyThrough(FollowUp::class, Casefile::class);
}