dt2015 2014-06-03 22:13
浏览 8
已采纳

Laravel 4多人同桌

I have a laravel 4 application and in this application I need to define a model with relation to another model 2 times but with discrimination on type.

Example

class Car extends Eloquent{

     public function oldDrivers(){
        return $this->hasMany('Driver');
     }

     public function newDrivers(){
        return $this->hasMany('Driver');
     }

}

so the relation will be the car Id at the driver's table, the thing is when I want to get the old drivers only for a certain car, it returns all drivers from both relations.

When looking into it I found because it is the same table, so now I set a type in the Driver model, now I want my relation to be filtered by this type, so the oldDrivers will be only drivers with the type of oldDrivers and new drivers will be the Drivers with only the newDriver type set,

How can this be done in Laravel ?

  • 写回答

1条回答 默认 最新

  • douan9541 2014-06-03 22:20
    关注

    You may try something like this:

    class Car extends Eloquent{
    
         public function oldDrivers(){
            return $this->hasMany('Driver')->where('type', 'olddrivers');
         }
    
         public function newDrivers(){
            return $this->hasMany('Driver')->where('type', 'newdrivers');
         }
    
     }
    

    Assumed that you have type field as a filter in your database. If I'm wrong about type field then you just change the field name to the right one because you got the idea that how can you add filter using a where clause.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊