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

Categories

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

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

1 Answer

use

public function index()
{

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...