【问题标题】:Laravel RelationshipsLaravel 关系
【发布时间】:2013-04-19 02:30:11
【问题描述】:

我一直在 documentation 中查看 Laravel 4 中的关系,我正在尝试解决以下问题。

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

所以基本上,我正在就如何将两者关联起来(belongsTo()?)然后将连接的数据传递给视图获得一些建议。

这是我目前所处的位置http://paste.laravel.com/pf3

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

天然气

【问题讨论】:

    标签: laravel belongs-to relationships laravel-4 eloquent


    【解决方案1】:

    您需要在两个模型中指定关系。一个是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');
        }
    
    }
    

    然后在路由或控制器中调用它如下:

    特定事件的过程(在这种情况下,id 为 1)

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

    特定课程的事件(在这种情况下,id 为 1)

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

    请参考 Laravel 4 文档,Eloquent ORM 部分:http://laravel.com/docs/eloquent#one-to-one

    【讨论】:

    • 嗨,不抱歉。一个事件只会有 1 门课程与之关联。
    • 然后,用 hasOne() 代替 hasMany 使用 belongsTo()
    • hasOne() 关系将“this”模型的“id”与相关表中的“foreignKey”匹配。 belongsTo() 关系将相关表的“id”与“this”模型上的“localKey”字段匹配。另一种思考方式是 belongsTo() 关系应该存在于具有链接到相关表 id 的字段的模型上。 hasOne() 关系应该存在于由相关表上的字段“链接到”的模型上。 -----话虽如此,鉴于OP说“事件表包含一个名为'course_id'的字段”,上述答案似乎是错误的方法
    【解决方案2】:

    这与@Marko Aleksić 的答案基本相同,但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
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-22
      • 2015-11-13
      • 2020-10-24
      • 2017-10-21
      • 2018-01-22
      • 2022-01-04
      • 2017-03-04
      相关资源
      最近更新 更多