2016-01-06 66 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? –

相关问题