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 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿