dongzouqie4220 2014-05-08 08:41
浏览 21
已采纳

Laravel Eloquent加入

I have below query in core php:

SELECT DISTINCT device_tocken FROM push_details JOIN users ON users.id=push_details.user_id

I have to integrate it in laravel 4

Application already have User extends Eloquent class

I created Push_details class as below

class Push_details extends Eloquent {

public $table = 'push_details';

public function User() {
    return $this->hasMany('\User','id');
}

}

    Table : users
        Primary key : id

    Table: push_details
        Primary key: id
        Foreign key: user_id belongsTo('users.id');

But i m not able to get expected result.

One more thing i didn't write anything in User's model yet.

  • 写回答

2条回答 默认 最新

  • dqkelut8423 2014-05-08 09:57
    关注

    Only way to join table is.. to join it, as Eloquent relations don't work using joins but separate queries with WHERE IN clauses. So this will do:

    DB::table('push_details')
       ->select('device_tocken')
       ->distinct()
       ->join('users','users.id','=','push_details.user_id')
       ->get();
    

    Above will return array of stdObject's so or if you need Eloquent Collection with Eloquent models as a result replace DB::table('push_details')->select... with PushDetails::select...

    Now, correct your relations, as they are wrong:

    // PushDetails model (as previously stated, I suggest renaming it to StudlyCase)
    public function user() {
        return $this->belongsTo('\User','user_id'); // user_id is may be omitted here
    }
    
    // User model
    public function pushDetails() {
        return $this->hasMany('\PushDetails','user_id'); // user_id is may be omitted here as well
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决