2016-01-06 64 views
1

這是我產品型號:()方法返回所有的模型實例,而不是一個實例中laravel

class Product extends Model 
    { 
     protected $primaryKey = 'product_id'; 
     public $guarded = ['created_at', 'updated_at']; 

     public function product_pics() 
     { 
      return $this->hasMany('App\ProductPics'); 
     } 

    } 

這是ProductPics型號:

class ProductPics extends Model 
{ 
    public $timestamps = false; 
    protected $fillable = ['pic_name']; 
    protected $primaryKey = 'pic_id'; 

    public function product() 
    { 
     return $this->belongsTo('App\Product'); 
    } 
} 

現在我想要在ProductController show()方法中獲取特定產品及其所有產品圖片。對於我這樣寫:

public function show ($id) 
     { 
      $product = Product::find($id)->with('product_pics')->get(); 
      return $product; 

      return view('main.pages.product')->with(['product'=> $product]); 
     } 

但事與願違,而我用find()方法只選擇一個模式,它返回一組與相關產品的圖片全部產品模型。

什麼是問題?

回答

3

這是因爲你在最後一部分使用了get()。刪除get()並更改方法的順序,因爲find()方法返回Illuminate\Database\Eloquent\ModelCollection

因此,要解釋你的情況發生了什麼:它發現和返回模型與給定的$id。然後,您在返回的Product模型上開始新的查詢,其中靜態方法with(..)然後get()將所有結果返回爲Collection

也許在編程風格更加清晰:

$product = Product::find($id); // SELECT * FROM products WHERE `id` = $id 
// $product is now the model Product with loaded data from the DB. 

$product = $product->with('product_pics')->get(); // SELECT * FROM products JOIN product_pics ON ... 
// $product var is replaced with the collection of all products of the DB. 

重寫你的方法如下,使其工作:

public function show ($id) 
{ 
    $product = Product::with('product_pics')->find($id); 

    return view('main.pages.product')->with(['product'=> $product]); 
} 
+0

是的,我試試這個已經和作品,但它不被接受邏輯上對我來說。但是不應該先找到模型然後獲取ProductPics? –

相關問題