2016-04-03 121 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