-
Notifications
You must be signed in to change notification settings - Fork 11.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Global select list not respected in belongsToMany relationship #22482
Comments
This repo is for bug tracking. Use the forums or slack channel for solving your issue |
I believe it is a bug, because the scope treatment is inconsistent across relationship. Here are steps needed to reproduce, so you have a full bug report: Steps to reproduce
class User extends Authenticatable
{
protected $fillable = ['name'];
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
}
class Permission extends Model
{
public static function boot()
{
parent::boot();
static::addGlobalScope(function(Builder $query) {
$query->select('name');
});
}
}
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('permissions', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->timestamps();
});
Schema::create('permission_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('permission_id');
$table->integer('user_id');
});
\App\User::create([
'name' => 'John Doe',
]);
Route::get('/', function () {
$user = \App\User::first();
DB::listen(function ($query) {
dump($query->sql);
});
$user->permissions()->get();
}); What is expectedOnly the select
`name`,
`permission_user`.`user_id` as `pivot_user_id`,
`permission_user`.`permission_id` as `pivot_permission_id`
from `permissions`
inner join `permission_user` on `permissions`.`id` = `permission_user`.`permission_id`
where `permission_user`.`user_id` = ? What is actually happeningAll columns are fetched from the select
`name`,
`permissions`.*,
`permission_user`.`user_id` as `pivot_user_id`,
`permission_user`.`permission_id` as `pivot_permission_id`
from `permissions`
inner join `permission_user` on `permissions`.`id` = `permission_user`.`permission_id`
where `permission_user`.`user_id` = ? |
Description:
I'm working with a legacy database with an enormous number of columns in tables and I want to fetch only few of them. Usually I restrict the column list globally by adding a query scope in the boot method of the model and it works fine with one-to-many relationships but with a many-to-many relationship all columns from the related table are being fetched.
This is because the scopes are applied after the column list on the query instance is checked in
BelongsToMany::get()
Is there a reason behind this? Can this order be reversed like so:
The text was updated successfully, but these errors were encountered: