我正在写一个样品的电子商务网站与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