Laravel关系 [英] Laravel Relationships

查看:166
本文介绍了Laravel关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在文档中查看Laravel 4中的关系,我正在努力解决以下。

I've been looking over relationships in Laravel 4 in the documentation and I'm trying to work out the following.

我的数据库中有一个名为events的表。此表具有主要包含与其他表相关的ID的各种字段。例如,我有一个'课程'表。事件表包含一个名为course_id的字段,它与课程表中的id字段的ID相关。

I have a table in my database called 'events'. This table has various fields that mainly contain ID's that relate to other tables. For example, I have a 'courses' table. The events table contains a field called 'course_id' which relates to the ID of the 'id' field in the courses table.

所以基本上,我经过一些建议关于如何关联两个(belongsTo()?),然后将连接的数据传递给视图。

So basically, I'm after some advice on how you go about relating the two (belongsTo()?) and then passing the connected data to the view.

这里是我到目前为止的一个 http://paste.laravel.com/pf3

Here is where I am at so far http://paste.laravel.com/pf3.

我希望你们能够就如何最好地解决这个问题给我一些建议。谢谢。

I hope you guys are able to give me some advice on how best to approach this problem. Thanks.

Gaz

推荐答案

这基本相同的答案@MarkoAleksić,但是hasOne()和belongsTo()关系正确的方法。

This is basically the same answer as @Marko Aleksić, but with the hasOne() and belongsTo() relationships the right way around.

class Course extends Eloquent{

    protected $table = 'courses';


    public function event()
    {
        return $this->hasOne('Event'); // links this->id to events.course_id
    }
}


class Event extends Eloquent {

    protected $table = 'events';

    public function course()
    {
        return $this->belongsTo('Course'); // links this->course_id to courses.id
    }

}

这篇关于Laravel关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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