[英]Many to many relations LARAVEL
I have a problem retrieving data from a third table, as you can see I have three tables:我在从第三个表中检索数据时遇到问题,如您所见,我有三个表:
I have as function :我有作为功能:
$model = model::paginate(10);
$level = level::all();
$models_level = models_level::all();
return view('pg',compact('model','level','models_level'));
How can I retrieve the level name based on the model id retrieved?如何根据检索到的模型 ID 检索级别名称?
Here is my blade这是我的刀片
<tbody>
@foreach($model as $f)
<tr class="item{{$f->id}}">
<td style="font-size: 13px;"> {{$f->title}}</td>
<td style="font-size: 13px;">{{$f->code}}</td>
<td style="font-size: 13px;">{{$f->models_level->level_id}}</td>
</tr>
@endforeach
{{ $filiere->links() }}
</tbody>
I need to show the title in level instead of the ID.我需要在级别而不是 ID 中显示标题。
in this case I have 2 different tables and the 3 rd is associative table that contains the two , so I have to pass by model to get model_level .在这种情况下,我有 2 个不同的表,第 3 个是包含这两个表的关联表,所以我必须通过模型来获取 model_level 。 get the level id depending on the model_id and the go to level and find the title ..根据model_id获取级别ID,然后转到级别并找到标题..
Models
– id
levels
– id
models_level
– product_id
– shop_id
here models_level table is called as pivot table app/Model.php这里models_level表被称为数据透视表app/Model.php
class Model extends Model
{
public function levels()
{
return $this->belongsToMany('App\level','models_level');
}
}
app/level.php应用程序/级别.php
class Level extends Model
{
public function Models()
{
return $this->belongsToMany('App\Shop','models_level');
}
}
$model = model::with('levels')->paginate(10);
return view('pg',compact('model'));
<tbody>
@foreach($model as $f)
<tr class="item{{$f->id}}">
<td style="font-size: 13px;"> {{$f->title}}</td>
<td style="font-size: 13px;">{{$f->code}}</td>
<td style="font-size: 13px;">{{$f->levels[0]->id}}</td>
</tr>
@endforeach
{{ $filiere->links() }}
</tbody>
You can read more about many to many relationships in the docs.您可以在文档中阅读有关多对多关系的更多信息。
I assume you are using a One to Many relationship and you have the correct methods in you model classes.我假设您使用的是一对多关系,并且您的模型类中有正确的方法。
This way you can change your controller method to:通过这种方式,您可以将控制器方法更改为:
$model = model::with('level')->paginate(10);
return view('pq', $model);
and in your blade files loop:并在您的刀片文件循环中:
<td style="font-size: 13px;">{{$f->level->title}}</td>
You should read up on eloquent relationships in the laravel documentation: https://laravel.com/docs/6.x/eloquent-relationships您应该阅读 laravel 文档中雄辩的关系: https ://laravel.com/docs/6.x/eloquent-relationships
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.