如何从中间表Laravel获取数据?

时间:2017-05-05 10:34:22

标签: laravel laravel-5 laravel-5.4

如何通过模型从第三个表中获取数据?

我有模型PrototypePrototypeField模型。

Prototype的位置:

id | name

PrototypeField的位置:

prototype_id | field_id

还有表Field,其中包含字段名称:

id | name 

如何通过模型'原型'从表Field获取名称其中PrototypePrototypeField的相对位置为:

Prototype.id = PrototypeField.prototype_id

因此,Prototype可以有一个或多个PrototypeField

1 个答案:

答案 0 :(得分:1)

你的原型模型里面应该有一个关系,它指定了它应该与之相关的字段,例如:

public function fields()
{
    return $this->belongsToMany('App\Fields'); // Change to location of fields model
}

您的字段模型还应包含一个关系,以指定与其相关的原型,例如:

public function prototypes()
{
    return $this->belongsToMany('App\Prototypes'); // Change to location of prototype model
}

完成设置之后,您就可以使用以下选项选择原型所属的字段:

Prototype::first()->fields; //This selects the first prototype and gets the associated fields.

其中的反转是:

Fields::first()->prototypes //This selects the first field and get associated prototypes.

通过阅读Laravel模型 - https://laravel.com/docs/5.4/eloquent-relationships

上的文档,您可以找到大量信息
相关问题