Question

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.

Was it helpful?

Solution

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
}

OTHER TIPS

  1. In your User model, you need to link back to the PushDetails model, like so

    class User extends Eloquent {
        public function push_details() {
            return $this->belongsTo('PushDetails');
        }
    }
    
  2. Use CamelCase for Class names, because laravel has several functions, in which CamelCase are changed to snake_case

  3. Change

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

to

    public function users() {
        return $this->hasMany('User');
    }

See the docs 'Eloquent ORM' for more...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top