繁体   English   中英

使用 Laravel Eloquent ORM 连接另外四个表

[英]Joining four more table using Laravel Eloquent ORM

我在产品表中有一个类别 ID、颜色 ID、尺寸 ID、品牌 ID。 如何使用 Eloquent ORM 关联所有表? 我想在产品 controller 中写一个查询,并将表中的所有数据都带进来。 如果没有查询生成器,我怎么能做到这一点?

您需要在产品 Model 中建立关系。

class Product extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category','category_id','id');
    }

    public function color()
    {
        return $this->belongsTo('App\Color','color_id','id');
    }
    public function size()
    {
        return $this->belongsTo('App\Size','size_id','id');
    }
    public function brand()
    {
        return $this->belongsTo('App\Brand','brand_id','id');
    }
}

现在在 controller 你可以得到如下。

$products = Product::with(['category','color','size','brand'])->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM