Php 使用with()方法和find()方法返回所有模型实例,而不是laravel中的一个实例
这是我的产品型号:Php 使用with()方法和find()方法返回所有模型实例,而不是laravel中的一个实例,php,laravel,Php,Laravel,这是我的产品型号: class Product extends Model { protected $primaryKey = 'product_id'; public $guarded = ['created_at', 'updated_at']; public function product_pics () { return $this->hasMany('App\Produ
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');
}
}
这是ProductPics型号:
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()方法仅选择一个模型,但它返回一组包含相关产品图片的所有产品模型
问题出在哪里?这是因为您在最后一部分使用了
get()
。删除get()
并更改方法的顺序,因为find()
方法返回的是illighte\Database\Eloquent\Model
或集合
因此,为了解释在您的案例中发生了什么:它查找并返回带有给定$id
的模型。然后,使用static方法和(…)
对返回的产品
模型启动一个新的查询,然后使用get()
将所有结果作为集合
返回
在编程风格上可能更清晰:
$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]);
}
是的,我已经试过了,而且很管用,但我不接受这种说法。但不应该先找到模型,然后再获取产品图片?