Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has many through with pivot table in Laravel4

I'm trying to setup a hasManyTrough relationship with Eloquent, but it's unclear how it works from the docs.

Tables:

users
   - id
   - firstname
   - ...etc

accounts
   - id
   - user_id
   - username
   - ...etc

roles
   - id
   - permissions

account_role
   - id
   - account_id
   - role_id

Models

<?php
class User extends Eloquent {

    public function account()
    {
        return $this->hasOne('Account');
    }

    // This is what I'm trying to achieve
    public function roles()
    {
        return $this->hasManyThrough('Role', 'Account');
    }
}

class Role extends Eloquent {

    public function accounts()
    {
        return $this->belongsToMany('Account')->withTimestamps();
    }
}

class Account extends Eloquent {

    public function user()
    {
        return $this->belongsTo('User');
    }
}

Error and question The error I'm gettings is: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.account_id' in 'on clause'

I know I can do something $user->account->roles, but I want to be able to do $user->roles. How do I set this up properly?

like image 623
DerLola Avatar asked Jun 17 '14 10:06

DerLola


1 Answers

In the end I was able to solve this by doing the following:

class User extends Eloquent {

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->account->belongsToMany('Navicula\Entities\Role');
    }
}

I suspected this would not eager load the Accounts, causing a lot of query overhead. However, when I tried it out using User::with('roles')->limit(100)->get(); and logged the queries, the following queries ran:

SELECT * FROM `users` WHERE `users`.`deleted_at` IS NULL LIMIT 100
SELECT * FROM `accounts` WHERE `accounts`.`deleted_at` IS NULL LIMIT 1
SELECT `roles`.*, `account_role`.`account_id` as `pivot_account_id`, `account_role`.`role_id` as `pivot_role_id` FROM `roles` inner join `account_role` on `roles`.`id` = `account_role`.`role_id` WHERE `account_role`.`account_id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '60', '61', '62', '63', '64', '65', '67', '68', '70', '71', '72', '73', '74', '75', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106')

Which is exactly what we want. Thanks Taylor ;-)

like image 156
DerLola Avatar answered Nov 01 '22 04:11

DerLola