简体   繁体   中英

Laravel How to get pivot table with selected option

I have pivot table

I want it to be selected based on what's in the database.

With the code I wrote in the selected option section, only the value of treatment_id 1 is returned. How can I get all treatments with doctor_id 1?

treatment_doctor

id | treatment_id|  doctor_id|
1  |    1        |    1      |
2  |    2        |    1      |
3  |    1        |    2      |

Treatment model

public function doctors()
    {
        return $this->belongsToMany(Doctor::class,'treatment_doctor','doctor_id','treatment_id')
    }

Controller

$treatments = Treatment::with('doctors')->get();

blade

 <select class="form-control" id="treatments" name="treatments[]" multiple="multiple">
   @foreach($treatments as $treatment)
    <option {{ collect($treatment->doctors->pluck('id')->toArray())->contains($treatment->id) ? 
    'selected' : '' }} value="{{ $treatment->id }}">{{ $treatment->name }}</option>
   @endforeach
 </select>

You can include data from your pivot table by calling ->withPivot() on your relationship
https://laravel.com/docs/9.x/eloquent-relationships#retrieving-intermediate-table-columns

To query based on the pivot table you can use ->wherePivot()
Full info here https://laravel.com/docs/9.x/eloquent-relationships#filtering-queries-via-intermediate-table-columns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM