skip to Main Content

Using Filament PHP, i’m facing a problem with a relation, I can access the resource create view, and save the content (with all the relations fine), but the error appear when I open the edit view of the resource.

I think I need to know how modify my code to make the Filament use the correct joins.

The error:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: ‘machines_power_supplies’

SELECT
  `machines_power_supplies`.*,
  `machines_power_supplies`.`machine_id` AS `pivot_machine_id`,
  `machines_power_supplies`.`model_id` AS `pivot_model_id`,
  `machines_power_supplies`.`name` AS `pivot_name`
FROM
  `machines_power_supplies`
  INNER JOIN `machines_power_supplies` ON `machines_power_supplies`.`id` = `machines_power_supplies`.`model_id`
WHERE
  `machines_power_supplies`.`machine_id` = 9

My Machine Model:

public function powerSupplies(): BelongsToMany
{
    return $this->BelongsToMany(MachinePowerSupply::class, 'machines_power_supplies', 'machine_id', 'model_id');
}

My Pivot Model:

public function machine(): BelongsTo
{
    return $this->belongsTo(Machine::class, 'machine_id', 'id');
}

public function option(): BelongsTo
{
    return $this->belongsTo(Option::class, 'model_id', 'id');
}

The Option model is a generic model use in other resources, with a list of contents:

<?php

namespace AppModelsOptions;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsBelongsTo;
use AppModelsOptionsOptionsList;

class Option extends Model
{
    use HasFactory;

    public $timestamps = false;
    protected $table = 'options';

    protected $fillable = [
        'options_list_id',
        'name',
        'value',
        'description',
    ];

    public function list(): BelongsTo
    {
        return $this->belongsTo(OptionList::class, 'options_lists_id');
    }
}

Here’s the part of the Form:

...
Select::make('power_supply_id')
    ->label(__('machines.power_supply'))
    ->relationship('powerSupplies', 'name')
    ->options(OptionService::getOptions('machine.power_supply'))
    ->multiple()
    ->searchable(),
...

2

Answers


  1. Chosen as BEST ANSWER

    After a hour... the obvious hit me hard! Changed the BelongsToMany, referencing the Option model, instead of pivot model.

    public function powerSupplies(): BelongsToMany
    {
        return $this->BelongsToMany(Option::class, 'machines_power_supplies', 'machine_id', 'model_id');
    }
    

  2. public function powerSupplies(): BelongsToMany {
    return $this->belongsToMany(MachinePowerSupply::class, ‘machines_power_supplies’, ‘machine_id’, ‘model_id’)
    ->withPivot(‘name’); // Assuming ‘name’ is the pivot column you’re interested in
    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search