简体   繁体   English

将数据库关系转换为Eloquent关系

[英]translating database relationships to Eloquent relationships

So, I've been trying to watch and read eloquent relationships from laracasts. 所以,我一直在努力观察和阅读来自laracasts的雄辩关系。 Unfortunately I still don't quite get how to translate database relationships to eloquent relationships (hasOne, belongsTo, hasMany, etc). 不幸的是,我仍然不太了解如何将数据库关系转换为雄辩的关系(hasOne,belongsTo,hasMany等)。

Let's say I have an Account and Customer tables. 假设我有一个帐户和客户表。 Account table has a "Customer_id" foreign key which references to the "id" on Customer table. 帐户表有一个“Customer_id”外键,它引用Customer表上的“id”。 Let's assume it's a one-to-many relationship. 我们假设它是一对多的关系。 How should I put it on my models on laravel? 我该如何把它放在laravel上的模特身上?

Which table should contain the "hasMany" and which one should have the "belongsTo"? 哪个表应该包含“hasMany”,哪个应该包含“belongsTo”?

Just think about how you would say it. 试想你会怎么说。 In your case it sounds like a Customer has many Accounts and an Account belongs to one Customer. 在您的情况下,它听起来像一个客户有很多帐户,一个帐户属于一个客户。

So you would put the hasMany() in your Customer model and the belongsTo() in your Account model. 因此,您可以将hasMany()放在Customer模型中,将belongsTo()放入Account模型中。

class Customer extends Model {

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

}

class Account extends Model {

    public function customer() {
        return $this->belongsTo('App\Customer');
    }

}

You can read more about Laravel database relationships here . 您可以在此处阅读有关Laravel数据库关系的更多信息。

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

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