I have a many to many relationship where the pivot table has a custom name with a prefix, so I'm trying to use the using method to set my custom pivot, but it doesn't changes anything on the output SQL query.
public function relation(): BelongsToMany
{
return $this->belongsToMany(Model\TableX::class)->using(Pivot\TableXY::class);
}
i dont think the using is intended to change the query, it just tells laravel what to do with the results (atleast for now, maybe a pr could change it)
to customize the table name, you can pass it as the 2nd parameter to belongsToMany, eg $this->belongsToMany(Model\TableX::class, 'custom_xy_table')
Thanks for the information.
That's really odd, I would (and actualy I am) need to instantiate my model just to take it's name, because if I use a ORM, I do use it to avoid query strings and that includes placing a string tablename. That's a very ugly side of Eloquent to use that much string controlled operations.
Maybe changing the using method is no the ideal, cause its an existing behavior and probably lots of devs use it. But, at least, it should have a method that accepts a Model or Pivot that changes the query based on the class.
That's my actual code:
public function permissions(): BelongsToMany
{
$pivotName = (new Entity\AccessControl\RolePermission)->getTable();
return $this->belongsToMany(Entity\AccessControl\Permission::class, $pivotName);
}
Stumbled into it just now. Expected for using to use method getTable() of Pivot class when getting relation. It seems, the only bypass for me is the last post here.
You can't really change that. By the time using() is called, the relationship query is already set up.
It would also break the existing relationships with using().
@laurencei Can be closed.
Although this one already closed, may I know what using method for ?
Or where should I ask ?
For thoose reading this, there is a better way to do it. You can pass directly the model class as the second argument, and it's table will be used, and the model will be used as pivot.
(see IlluminateDatabaseEloquentRelationsBelongsToMany::resolveTableName)
With the @odahcam example:
public function permissions(): BelongsToMany
{
return $this->belongsToMany(
Entity\AccessControl\Permission::class,
Entity\AccessControl\RolePermission::class
);
}
That's perfect. I actually tried in the time I used it to make it this way, but that was not possible at that time. I also remember getting pretty angry with the framework because of that, hehe.
Most helpful comment
For thoose reading this, there is a better way to do it. You can pass directly the model class as the second argument, and it's table will be used, and the model will be used as pivot.
(see IlluminateDatabaseEloquentRelationsBelongsToMany::resolveTableName)
With the @odahcam example: