简体   繁体   English

Laravel关系

[英]Laravel Relationships

I've been looking over relationships in Laravel 4 in the documentation and I'm trying to work out the following. 我一直在文档中查看Laravel 4中的关系,我正在努力解决以下问题。

I have a table in my database called 'events'. 我的数据库中有一个名为'events'的表。 This table has various fields that mainly contain ID's that relate to other tables. 该表具有各种字段,主要包含与其他表相关的ID。 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. 事件表包含一个名为“course_id”的字段,该字段与courses表中“id”字段的ID相关。

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. 所以基本上,我正在讨论如何关联两者(belongsTo()?)然后将连接的数据传递给视图。

Here is where I am at so far http://paste.laravel.com/pf3 . 这是我到目前为止的地方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 GAZ

This is basically the same answer as @Marko Aleksić, but with the hasOne() and belongsTo() relationships the right way around. 这与@MarkoAleksić的答案基本相同,但是hasOne()和belongsTo()关系正确。

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
    }

}

You need to specify in both models a relationship. 您需要在两个模型中指定关系。 belongsTo() in one, hasOne() in the other, since you are using one-to-one relationship belongsTo()在一个,另一个是hasOne(),因为你使用的是一对一的关系

class Course extends Eloquent{

    protected $table = 'courses';


    public function event()
    {
        return $this->belongsTo('Event');
    }
}


class Event extends Eloquent {

    protected $table = 'events';

    public function course()
    {
        return $this->hasOne('Course');
    }

}

Then calling it in the route or the controller would be as following: 然后在路由或控制器中调用它将如下:

Course of specific event (in this case with id of 1) 特定事件的过程(在这种情况下,id为1)

$course = Event::find(1)->course;

Event of specific course (in this case with id of 1) 特定课程的事件(在这种情况下,id为1)

$event = Course::find(1)->event;

Please refer to the Laravel 4 documentation, section Eloquent ORM: http://laravel.com/docs/eloquent#one-to-one 请参阅Laravel 4文档,Eloquent ORM部分: http ://laravel.com/docs/eloquent#one-to-one

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

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