Laravel5:如何在数据库中表达雄辩的模型关系? [英] Laravel5: How are Eloquent model relationships expressed in the database?

查看:89
本文介绍了Laravel5:如何在数据库中表达雄辩的模型关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解缺少的链接.

There's a missing link I fail to understand.

我使用迁移来创建数据库表,并在那里定义关系.意思是..如果我有一个人员表和一个工作表,并且我需要人与工作之间的一对多关系,我希望该工作表包含一个"person_id".

I use migrations to create database tables and I define the relationships there. meaning.. if I have a person table and a job table and I need a one to many relationship between the person and jobs, I'd have the job table contain a "person_id".

当我播种数据或将其添加到我的应用程序中时,我将完成添加设置* _id =值等的记录的所有工作.

When I seed data or add it in my app, I do all the work of adding the records setting the *_id = values etc.

但是以某种方式,我觉得Laravel有更好的方法做到这一点.

but somehow I feel Laravel has a better way of doing this.

如果我定义与oneToMany Laravel雄辩的一对多关系:

if I define that one to many relationship with the oneToMany Laravel Eloquent suports:

在我的Person模型中.....

in my Person model.....

 public function jobs()
    {
        return $this->hasMany('Jobs);
    }

在数据库级别上做了什么?如何为该表创建迁移? Laravel是在这里自动完成预期"的事情吗?喜欢寻找Jobs表,并在那里有一个"person_id"?

what's done on the database level? how do I create the migration for such table? Is Laravel automagically doing the "expected" thing here? like looking for a Jobs table, and having a "person_id" there?

推荐答案

是的,Laravel正在做您在最后一段中所做的猜测.

Yep, Laravel is doing what you guess in your last paragraph.

来自有关口才关系的Laravel文档(相关段落以粗体显示):

From the Laravel documentation for Eloquent Relationships (with the relevant paragraph in bold):

例如,一个User模型可能有一个Phone.我们可以定义这个 雄辩的关系:

For example, a User model might have one Phone. We can define this relation in Eloquent:

class User extends Model {

    public function phone()
    {
        return $this->hasOne('App\Phone');
    }

}

传递给hasOne方法的第一个参数是 相关模型.关系定义好后,我们可以检索它 使用Eloquent的动态属性:

The first argument passed to the hasOne method is the name of the related model. Once the relationship is defined, we may retrieve it using Eloquent's dynamic properties:

$phone = User::find(1)->phone;

此语句执行的SQL 将如下所示:

The SQL performed by this statement will be as follows:

select * from users where id = 1

select * from phones where user_id = 1

请注意,Eloquent会根据模型名称假定关系的外键.在这种情况下,假定Phone模型使用user_id外键.

Take note that Eloquent assumes the foreign key of the relationship based on the model name. In this case, Phone model is assumed to use a user_id foreign key.

还要注意,您实际上不必在数据库中显式设置外键索引(仅使那些具有与父键列相同数据类型的外键"列就足以使Laravel接受该关系) ,尽管您可能应该为了数据库完整性而拥有这些索引.

Also note that you don't actually have to explicitly set the foreign key indexes in your database (just having those "foreign key" columns with the same data type as the parent key columns is enough for Laravel to accept the relationship), although you should probably have those indexes for the sake of database integrity.

这篇关于Laravel5:如何在数据库中表达雄辩的模型关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆