2016-04-03 122 views
0

我正在写一个样品的电子商务网站与Laravel 5 之间的关系我有2个表: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(); 
}); 

Schema::create('featureds', function (Blueprint $table) { 
    $table->integer('product_id')->unique()->unsigned(); 
}); 

Schema::table('featureds', function($table) { 
    $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade'); 
}); 

模式

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'); 
    } 
} 

然后,我有一个Controller,我在那里坐4 featured products

$featured_products = Featured::limit(4)->get(); 
return view('home', ['featured_products' => $featured_products]); 

现在,我想展现在我看来,这些特色产品。如果我从Featured model显示product_id,一切都很好:

@foreach($featured_products as $prod) 
    {{$prod->product_id}} 
@endforeach 

但我想采取通过精选提到的product的名称。我想是这样的:

@foreach($featured_products as $prod) 
    @foreach($prod as $p) 
    {{$p->name}} 
    @endforeach 
@endforeach 

因为featured_products(在controller)似乎是一个集合,但它不工作!

回答

0

在你Featured模式,你必须在方法product()的关系,当你想从视图访问的关系,你可以调用该方法的名称属性,在你的情况下,你有一个方法叫product()所以你必须调用product属性是这样的:

@foreach($featured_products as $prod) 
    {{ $prod->product->name }} 
@endforeach 

根据您在模型中配置的关系,它会自动写入product name

参考:https://laravel.com/docs/5.2/eloquent-relationships

编辑:

对不起是我不好,我猜你是定义一个错误的关系,你的Product模型,应该有一个使用hasOne关系的featured()方法,而Featured模型应该有一个product()使用belongsTo关系的方法。因此,在App\Featured你的模式,你必须定义这样的关系:

return $this->belongsTo('App\Product'); 

而在你App\Product模型,你应该定义关系,像这样:

return $this->hasOne('App\Featured'); 

希望工程

+0

嗨,第一感谢您的帮助。 我试过这种方式,但是它返回这个: 'ConnectionException.php中的ErrorException 673行: SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'products.product_id'(SQL:select * from 'product'where'product','product_id'为null和'products'。'product_id'不为null limit 1)(View:/ home/vagrant/Code/projects/mwt-lamp/resources/views/widgets/featured .blade.php)(查看:/home/vagrant/Code/projects/mwt-lamp/resources/views/widgets/featured.blade。PHP)' – luca89pe

+0

对不起,我想你定义了一个错误的关系,你的'Product'模型应该有一个'featured()'方法,它使用'hasOne'关系,而'Featured'模型应该有一个'product )'使用'belongsTo'关系的方法。因此,在您的App \ Featured模型中,您必须像这样定义关系'return $ this-> belongsTo('App \ Product');'。而在你的App \ Product'模型中,你应该像'return $ this-> hasOne('App \ Featured');'定义关系。希望工程 –

+0

呀,它的作品,我只是改变了'hasOne'到'belongsTo'对函数'产品()''到模型Featured'。 你可以编辑答案,所以我可以将其设置为答案? 谢谢 – luca89pe