Php laravel 5:产品与特色产品的关系
我正在用Laravel 5编写一个电子商务网站示例。 我有两张桌子:Php laravel 5:产品与特色产品的关系,php,laravel-5.2,laravel-blade,table-relationships,Php,Laravel 5.2,Laravel Blade,Table Relationships,我正在用Laravel 5编写一个电子商务网站示例。 我有两张桌子: Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->text('description'); $table->float('price'); $table->integer('cat
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->float('price');
$table->integer('category_id');
$table->timestamps();
});
及
型号
class Product extends Model
{
public function category(){
return $this->belongsTo('App\Category');
}
}
class Featured extends Model
{
public function product(){
return $this->hasOne('App\Product', 'product_id');
}
}
然后,我有一个控制器
,在那里我拿了4个特色产品
:
$featured_products = Featured::limit(4)->get();
return view('home', ['featured_products' => $featured_products]);
现在,我正试图以我的视角展示这些特色产品。如果我显示了特色车型的产品id
,一切正常:
@foreach($featured_products as $prod)
{{$prod->product_id}}
@endforeach
但是,我想取特约记者提到的产品的名称。我试着这样做:
@foreach($featured_products as $prod)
@foreach($prod as $p)
{{$p->name}}
@endforeach
@endforeach
因为特色产品
(在控制器
中)似乎是一个集合,但它不起作用 在您的特色
模型中,您在方法product()
中有一个关系。当您想从视图访问该关系时,您可以将方法名称作为属性调用,在您的情况下,您有一个名为product()
的方法,因此您必须调用product
属性,如下所示:
@foreach($featured_products as $prod)
{{ $prod->product->name }}
@endforeach
return $this->belongsTo('App\Product');
它将根据您在模型中配置的关系自动写入产品名称
参考:
编辑:
对不起,我的错,我猜你定义了一个错误的关系,你的产品
模型应该有一个featured()
方法使用hasOne
关系,而featured
模型应该有一个Product()
方法使用belongsTo
关系。因此,在您的App\Featured
模型中,您必须定义如下关系:
@foreach($featured_products as $prod)
{{ $prod->product->name }}
@endforeach
return $this->belongsTo('App\Product');
在您的App\Product
模型中,您应该这样定义关系:
return $this->hasOne('App\Featured');
希望它能起作用嗨,首先谢谢你的帮助。我尝试了这种方法,但它返回以下结果:ErrorException in Connection.php第673行:SQLSTATE[42S22]:未找到列:1054未知列'products.product\u id'位于'where子句'中(SQL:select*from'products'其中'products'。'product\u id'为null且'products'。'products\u id'不为null限制1)(View:/home/vagrant/Code/projects/mwt-lamp/resources/views/widgets/featured.blade.php)(View:/home/vagrant/Code/projects/mwt-lamp/resources/views/widgets/featured.blade.php)
对不起,我的错了,我猜你定义了一个错误的关系,你的产品
模型应该有一个featured()
方法使用hasOne
关系,而Featured
模型应该有一个product()
方法使用belongsTo
关系。因此在App\Featured
模型中,必须定义如下关系返回$this->belongsTo('App\product'))
。在您的App\Product
模型中,您应该定义这样的关系return$this->hasOne('App\Featured');
。希望它能工作是的,它能工作,我刚刚在函数Product()上将hasOne
更改为belongsTo
进入特色
模型。您能编辑答案吗,这样我就可以将其设置为答案?谢谢好的,我已经编辑了我的答案,谢谢,很高兴它能工作!干杯!