Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
986 views
in Technique[技术] by (71.8m points)

eloquent - belongsToManyRelation not working in laravel 8

I have many to many relation which is inserting data correctly but when I try to fetch data it gives me no data.

one table is boss and other is workers

Migration

<?php



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


Boss model relation

  public function workers()
    {
        return $this->belongsToMany(AppModelsAdminWorker::class,'boss_worker');
    }

How I am trying to fetch data

public function index()
{

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

}

How I am inserting data


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

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

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

It is not fetching any data

question from:https://stackoverflow.com/questions/66065784/belongstomanyrelation-not-working-in-laravel-8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use

public function index()
{

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...