存储belongsToMany关系的条件 - Laravel

时间:2016-10-01 05:46:55

标签: laravel eloquent

对于我的多对多关系,我有以下表格:soldhomesteststaskssoldhomestest_task(作为支点)。

我的soldhomestests表已经填充了数据。在创建满足我的soldhomestest表中条件的新任务时,如何让我的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');
    }

2 个答案:

答案 0 :(得分: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');
    }

答案 1 :(得分: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();
     }
}