使用with()方法与find()方法一起返回所有模型实例,而不是laravel中的一个实例


using with() method Along with find() method return all model instances instead one instance in laravel

这是我的产品型号:

class Product extends Model
    {
        protected $primaryKey = 'product_id';
        public    $guarded    = ['created_at', 'updated_at'];
        public function product_pics ()
        {
            return $this->hasMany('App'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()方法只选择一个Model时,它返回了一组包含相关Product图片的所有Products模型。

什么是问题?

这是因为您在最后一部分使用了get()。删除get()并更改方法的顺序,因为find()方法返回Illuminate'Database'Eloquent'ModelCollection

因此,为了解释您的案例中发生了什么:它找到并返回具有给定$id的模型。然后,使用static方法with( .. )get()对返回的Product模型启动一个新查询,以将所有结果作为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]);
}