我正在寫一個樣品的電子商務網站與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
)似乎是一個集合,但它不工作!
嗨,第一感謝您的幫助。 我試過這種方式,但是它返回這個: '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
對不起,我想你定義了一個錯誤的關係,你的'Product'模型應該有一個'featured()'方法,它使用'hasOne'關係,而'Featured'模型應該有一個'product )'使用'belongsTo'關係的方法。因此,在您的App \ Featured模型中,您必須像這樣定義關係'return $ this-> belongsTo('App \ Product');'。而在你的App \ Product'模型中,你應該像'return $ this-> hasOne('App \ Featured');'定義關係。希望工程 –
呀,它的作品,我只是改變了'hasOne'到'belongsTo'對函數'產品()''到模型Featured'。 你可以編輯答案,所以我可以將其設置爲答案? 謝謝 – luca89pe