关于Laravel中一些数据模型关系的快速查询.
我有一个属于用户的产品,但用户可以拥有许多产品.但是产品也可以让很多人对该产品提供报价;
class Product extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function offer(){
return $this->hasMany('App\Offer');
}
Run Code Online (Sandbox Code Playgroud)
但是产品也可以有不同的子类型的产品,例如,一个可能是车辆或手机,每个在我的迁移中都有不同的列,所以我假设我需要变形很多
在 Product.php
public function imageable()
{
return $this->morphTo();
}
Run Code Online (Sandbox Code Playgroud)
在 Vehicle.php
public function products()
{
return $this->morphMany('App\Product', 'imageable');
}
Run Code Online (Sandbox Code Playgroud)
但是,在致电时:
$product = Product::findOrFail($id);
Run Code Online (Sandbox Code Playgroud)
当我尝试做任何事情时,我得到null $product->vehicle
我将数据库中车辆的ID添加到imageable_id产品表中,并将产品表imageable中的车辆类型添加到"车辆".
我在这做错了什么?
一切看起来都正确你应该通过以下方式访问它imageable:
$product = Product::findOrFail($id);
return $product->imageable;
Run Code Online (Sandbox Code Playgroud)
从Laravel 文档:
您还可以通过访问执行对morphTo的调用的方法的名称,从多态模型中检索多态关系的所有者.
在您的情况下,执行调用的方法morphTo是可成像的.
| 归档时间: |
|
| 查看次数: |
3021 次 |
| 最近记录: |