2016-10-01 72 views
0

我有我的多對多關係的以下表格:soldhomestests,taskssoldhomestest_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'); 
    } 
+0

您可以使用雄辯事件。 https://laravel.com/docs/master/eloquent#events –

回答

0

不相信這是Laravel方式,但我使用where條件修改了我的控制器創建一個ID數組:

public function store(Request $request) 
    { 
     $this->validate($request, [ 
      'address' => 'required|max:255', 
      'city' => 'required|max:255', 
      'state' => 'required|max:255', 
     ]); 

     $newtask = $request->user()->tasks()->create([ 
      'address' => $request->address, 
      'city' => $request->city, 
      'state' => $request->state, 
     ]); 

     $condition = DB::table('soldhomestests')->where([ 
      ['soldhomestests.address', '=', $request->address], 
      ['soldhomestests.city', '=', $request->city], 
      ])->pluck('id'); 

     $lastid = $newtask->id; 
     $tasksoldhome = Task::find($lastid); 
     $tasksoldhome->soldhomestests()->sync($condition); 

     return redirect()->route('settings.index'); 
    } 
0

使用雄辯,你可以這樣做。

$task=new Task(); 
$task->city=$request->city; 
$task->address=$request->address; 
$task->save(); 

$soldhometests=Soldhometest::all(); 
foreach($soldhometests as $soldhometest) 
{ 
    if($task->city==$soldhometest->city && $task->address==$soldhometest->address) 
    {  
      $soldhometest_task=new SoldhometestTask(); // pivot model 
      $soldhometest_task->task_id=$task->id; 
      $soldhometest_task->soldhometest_id=$soldhometest->id; 
      $soldhometest_task->save(); 
    } 
}