laravel / ideas

Issues board used for Laravel internals discussions.
940 stars 28 forks source link

Respect model casting while querying a model #856

Open themsaid opened 7 years ago

themsaid commented 7 years ago

Original Issue: https://github.com/laravel/framework/issues/12238


This might be related to #5578, but if I have a model that uses $casts, then the firstOrCreate() always creates a new instance. For example:

class MyModel extends \Illuminate\Database\Eloquent\Model {

  $casts = [
    'field' => 'array'
  ];
}

$data = [
  'field' => [1,2,3]
];

// creates a new model
$model = MyModel::firstOrCreate($data); 

//...

// also creates a new model instead of retrieving the first one
$model2 = MyModel::firstOrCreate($data);
themsaid commented 7 years ago

A related change was applied and was reverted in: https://github.com/laravel/framework/pull/15018

staudenmeir commented 6 years ago

Casting the attributes doesn't solve the issue for JSON values. At least on MySQL, you can't query a JSON column by using ->where('field', json_encode([1, 2, 3])).

gareth-ib commented 5 years ago

I am having problems with this in laravel/framework v6.2.0. Is anyone working on this issue?

andrey-helldar commented 4 years ago

@themsaid, it seems to me that the changes proposed in laravel/framework#30958 PR will allow this to be implemented in custom castes.

gareth-ib commented 4 years ago

@andrey-helldar that'd be great! it's horrible that the original code was written in a way that broke this feature in the first place. thanks for fixing it!

sisve commented 4 years ago

@andrey-helldar Your PR seems to handle the casting of values, but it's not clear how you modify the behavior of firstOrCreate. Could you explain further how that PR solves this issue?

andrey-helldar commented 4 years ago

@sisve, the developer himself will be able to create custom types of objects processed both when they are received from the database and when they are written (create, update). I assume that you will be able to specify the behavior on your own and, as it were, tell the application in which specific form it is necessary to convert the value.

sisve commented 4 years ago

@andrey-helldar I'm not sure you can properly assume that. Does your PR modify how Laravel filters on values? If I were to >where('field', [1, 2, 3]), would the suggested Castable implementation (or the builtin casting logic) trigger for that field?

andrey-helldar commented 4 years ago

@sisve, I think not, such a method will not work because Cast is an extension of Eloquent while the where method is called from QueryBuilder, and this functionality does not affect it.