我有我的多對多關係的以下表格:soldhomestests
,tasks
和soldhomestest_task
(作爲數據透視表)。商店belongsTo與許多關係w /條件 - Laravel
我的soldhomestests表已經填充了數據。在創建滿足我的soldhomestst表中的條件的新任務時,如何讓我的soldhomestest_task數據透視表填充數據?在我的例子,我想存儲當滿足以下條件的關係數據:
'tasks.city' = 'soldhomestests.city'
'tasks.address' = 'soldhomestests.address'
我似乎無法找到如何與此進行任何文件?
機型:
class Task extends Model
{
protected $fillable = [
'address', 'city', 'state',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function soldhomestests()
{
return $this->belongsToMany('App\Soldhomestest');
}
}
class Soldhomestest extends Model
{
public function tasks()
{
return $this->belongsToMany('App\Task');
}
}
控制器:
public function store(Request $request)
{
$this->validate($request, [
'address' => 'required|max:255',
'city' => 'required|max:255',
'state' => 'required|max:255',
]);
$request->user()->tasks()->create([
'address' => $request->address,
'city' => $request->city,
'state' => $request->state,
]);
return redirect()->route('settings.index');
}
您可以使用雄辯事件。 https://laravel.com/docs/master/eloquent#events –