简体   繁体   English

Laravel 5.4 | 从数据透视表中获取数据

[英]Laravel 5.4 | Fetching data from Pivot Table

I have 4 tables in my database: 我的数据库中有4个表:

Table 1: Category 表1:类别

---|------
id | name
---|------
1  | Cars

In 'Category' model class I have defined the following relationship: 在“类别”模型类中,我定义了以下关系:

class Category {
    public function fields() {
        return $this->belongsToMany('App\Field');
    }
}

Table 2: Field 表2:字段

id | name
---|-------
1  | Make

In 'Field' model class I have defined the following relationship: 在'Field'模型类中,我定义了以下关系:

class Field {
    public function categories() {
        return $this->belongsToMany('App\Category');
    }
}

Table 3: Field_Options 表3:Field_Options

field_id | value
---------|-------
1        | Audi
1        | BMW

In 'FieldOption' model class I have defined the following relationship: 在'FieldOption'模型类中,我定义了以下关系:

class FieldOption extends Model
{
    public function field() {
        return $this->belongsTo('App\Field');
    }
}

Table 4: Category_Field 表4:Category_Field

category_id | field_id
------------|-------
1           | 1

Now I need to fetch all the fields and field_options for category_id=1. 现在我需要获取category_id = 1的所有字段和field_options。 How can I achieve this using Laravel? 如何使用Laravel实现这一目标?

Thanks! 谢谢!

First define relationship between Field and FieldOptions 首先定义Field和FieldOptions之间的关系

public function options() {
    return $this->hasMany('App\FieldOption');
}

Then you can eager load all relationships like this 然后你可以急切加载这样的所有关系

$category = Category::with('fields.options')->find(1);
//Get category 1, with all fields and their respectif fieldOptions

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

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