0

我有多对多关系,可以正确插入数据,但是当我尝试获取数据时,它没有给我任何数据。

一张桌子是老板,另一张是工人

Migration

<?php



public function up()
{
Schema::create('boss_worker', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('worker_id');
$table->unsignedBigInteger('boss_id');
$table->timestamps();
});
}


老板型号关系

  public function workers()
    {
        return $this->belongsToMany(\App\Models\Admin\Worker::class,'boss_worker');
    }

我如何尝试获取数据

public function index()
{

$boss = Boss::find(1);
dd($boss->workers);

}

我如何插入数据


$input = $request->all();
$workers = $input['workers'];
$input['workers'] = implode(',', $workers);

$boss = Boss::where('staff_id',$request->boss)->first();

$worker_gangs = $boss->workers()->sync($workers);

它没有获取任何数据

4

2 回答 2

0

利用

public function index()
{

$boss = Boss::with('workers')->find(1);

}
于 2021-02-05T15:20:50.377 回答
0

当您从要调用的模型中调用关系时,您可以使用Query BuilderIlluminate\Database\Eloquent\Builder访问和应用任何过滤器或查询,要从该关系中获取数据,您必须使用这些方法来执行查询

->get();
->first();

你的代码必须是:

$boss = Boss::find(1);
$workers = $boss->workers()->get();
dd($workers);

或者您可以使用 Boss 模型进行预加载

$boss = Boss::with('workers')->find(1);
dd($boss->workers);

于 2021-02-05T15:25:44.920 回答