Skip to content
This repository has been archived by the owner on Jul 16, 2021. It is now read-only.

Respect model casting while querying a model #856

Open
themsaid opened this issue Oct 26, 2017 · 9 comments
Open

Respect model casting while querying a model #856

themsaid opened this issue Oct 26, 2017 · 9 comments

Comments

@themsaid
Copy link
Member

Original Issue: laravel/framework#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
Copy link
Member Author

A related change was applied and was reverted in: laravel/framework#15018

@staudenmeir
Copy link

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
Copy link

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

@andrey-helldar
Copy link

@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
Copy link

@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
Copy link

sisve commented Dec 28, 2019

@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
Copy link

@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
Copy link

sisve commented Dec 29, 2019

@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
Copy link

@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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants