Reputation: 1101
Is it possible for the same eloquent query to generate mysql which sometimes writes to a specific column in a specific table and sometimes writes to a column with the same name in a pivot table?
Upvotes: -1
Views: 32
Reputation: 385
I assume that the condition for using the main table or the pivot is determined by one or more request parameters, so in Eloquent this should work:
class MyModel extends Model
{
/** @var string Column name */
const SHARED_COLUMN = 'column_name';
/**
* Update the 'SHARED_COLUMN' column value.
*/
public function setSharedColumnValue($validatedRequest)
{
if ($this->shouldUsePivotTable($validatedRequest)) {
$this->pivot->{self::SHARED_COLUMN} = $value;
$this->pivot->save();
} else {
$this->update(self::SHARED_COLUMN, $value);
}
}
/**
* Here you can define your logic.
*/
private function shouldUsePivotTable(array $options = []): bool
{
return ! empty($options['value1'])
&& ! empty($options['value2'])
&& $options['value1'] === 'abc'
&& $options['value2'] === 'def';
}
/**
* Create a new MyModule instance.
*/
public function createFromRequest($validatedRequest): self
{
$instance = self::fill($validatedRequest)->save();
$instance->setSharedColumnValue($validatedRequest);
return $instance;
}
/**
* Update a MyModule instance.
*/
public function updateFromRequest($validatedRequest): self
{
$this->fill($validatedRequest)->save();
$this->setSharedColumnValue($validatedRequest);
return $this;
}
}
class MyController extends controller
{
public function store(StoreRequest $request)
{
MyModel->createFromRequest($request->validated();
return 'My Model created!';
}
public function update(UpdateRequest $request, MyModel $myModel)
{
$myModel->updateFromRequest($request->validated();
return 'My Model updated!';
}
}
Upvotes: 0