Php 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

我正在用Laravel 5编写一个电子商务网站示例。 我有两张桌子:

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
进入
特色
模型。您能编辑答案吗,这样我就可以将其设置为答案?谢谢好的,我已经编辑了我的答案,谢谢,很高兴它能工作!干杯!