Ad

How To Scope Results With Pivot Table October Cms

- 1 answer

The solution to this is probably easy and I'm just missing it, but I can't seem to figure out how to limit "customers" based on the "user" that the customer belongs to.

This is a many to many relationship, so a customer can belong to more than one user and a user can have more than one customer.

Here is my relationship definition:

public $belongsToMany = [
    'user_id' => [
        'RainLab\User\Models\User',
        'table' => 'tablename_users_customers',
    ]
];

And here is the scope function that doesn't work as I'd expect:

public function scopeUser($query) {
    $user = Auth::getUser()->id;
    return $query->where('user_id', $user)->get();
}

Finally, here is my error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from `tblcustomers` where `user_id` = 1)

Obviously, the error is because the "user_id" column doesn't exist in the 'tblcustomers' table, but rather in the pivot table. How can I use the "user_id" from the pivot table in my scope function? I need to only display Customers that belong to the currently logged in user.

Ad

Answer

Yes this can be possible

But First thing is you need to remove get() method from the scope, scope meant to return query object for chaining methods further.

Your relation and scope should look like this

// relation
public $belongsToMany = [
    // PLEASE MAKE RELATION NAME CORRECT HERE
    'users' => [  // not user_id, use `users`
        'RainLab\User\Models\User',
        'table' => 'tablename_users_customers',
        // 'key' => 'customer_id', if needed
        // 'otherKey' => 'user_id' if needed
    ]
];


// scope
use RainLab\User\Models\User;
public function scopeUser($query) {    
    return $query->whereHas('users', function($usersQuery) {
        $user_id = Auth::getUser()->id;
        return $usersQuery->where((new User)->getTable() . '.id', $user_id);       
    });
}

// usage
$result = Customer::user()->get();
dd($result);  
// you will get only customers which has relation with current logged in user. 

if any doubts please comment.

Ad
source: stackoverflow.com
Ad