[英]Laravel Pivot Table belongsToMany
我是php和Laravel的新手,所以我有很多疑问。 我正在使用phpmyadmin并具有下一个关系:
Table:| productos | tipos | marcas | producto_tipo_marca (pivot table)
| id | id | id | id
| id_tipo | nombre | nombre | id_producto
| id_marca | | | id_tipo
| | | | id_marca
(我的工作用英语命名)因此,表product(productos)具有一个foreing_keys id_type(id_tipo)和id_brand(id_marca)的名称。 产品与类型和品牌有很多关系。
问题1:是否需要数据透视表? (对不起,但我一个人在工作,很怀疑)
我一直在使用jquery并列出数据(都很好),但是在product.index上,我想显示id_type-> nambe和id_brand-> nambe,但我能在数据表上显示的是id_type和id_brand(显示仅数字数据):
查看:product.index
@foreach($products as $product)
<td>{{ $product->id_type}}</td>
<td>{{ $product->id_brand }}</td>
@endforeach
当我做类似的事情时:
@foreach($products as $product)
<td>{{ $product->id_type->name}}</td>
<td>{{ $product->id_brand->name}}</td>
@endforeach
发生错误:尝试获取非对象的属性(视图:C:\\ xampp \\ htdocs \\ posm \\ app \\ views \\ productos \\ index.blade.php)
因此,我看了很多教程,但是却找不到核心。
在我的模型中有:
产品(型号)
protected $guarded = array();
protected $table = 'products';
protected $fillable = array('id_type','id_brand');
问题2:我是否需要指定类似的东西:id_type-> name或我不能这样做?
类型(型号)
protected $guarded = array();
protected $table = 'type';
protected $fillable = array('name');
public function products(){
return $this->belongsToMany('Product'); //Access the model Product.
}
品牌(型号)
protected $guarded = array();
protected $table = 'brand';
protected $fillable = array('name');
public function products(){
return $this->belongsToMany('Product'); //Access the model Product.
}
ProductController的
public function index()
{
$products = $this->product->all();
return View::make('product.index', compact('product'));
}
问题3:我是否需要在此处添加一些代码来指定产品是否要获得id_type-> name和id_brand-> name还是让它像我拥有的一样?
问题:我需要做什么? ¿只是要在我的jquery数据表上获取id_type-> name和id_brand-> name? 我需要一个数据透视表,并在模型和控制器上做一些代码? 或者可以直接在view product.blade上获得类型和品牌名称?
对不起,很长的问题。 我将不胜感激。 谢谢!
我不是MySQL高级用户,但我认为您不需要数据透视表。 您需要使用以下表格:productos,tipos和marcas。
如果要从“产品”模型访问数据,则需要在Product.php中添加以下关系:(我不知道您是使用英语还是西班牙语编写代码)。
public function type()
{
return $this->belongsTo('Type', 'type_id');
}
public function brand()
{
return $this->belongsTo('Brand', 'brand_id');
}
如果需要在每个查询上自动加载此关系,则需要添加以下属性:
public $with = ['type', 'brand'];
如果没有,您可以在进行查询时指定,而不是添加$ with属性,如下所示:
Product::with(['type', 'brand'])->get();
然后,您可以执行以下操作:
$products = Product::with(['type', 'brand'])->get();
并在视图中:
@foreach($products as $product)
{{ $product->type->name }}
{{ $product->brand->name }}
@endforeach
我没有测试代码,因此请在使用前检查它!
Laravel文档很棒,您应该看一下: http : //laravel.com/docs/4.2/eloquent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.