Eloquent relationship from JSON with Laravel
Tesettur-Pazari opened this issue · 4 comments
I want to get the category of a product using the Eloquent relationship. However, the categories of products are stored in the json value in the products table.
products table
------------------------------------------------
id | ProductName | Categories
------------------------------------------------
1 Uzun Mavi Elbise ["1","4"]
2 Kısa Kuyruklu Tunik ["2"]
categories table
-----------------
id | CategoryName
-----------------
1 Elbise
2 Tunik
3 Abiye
4 Kışlık Elbise
Use a BelongsToJson
relationship:
class Product extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = [
'Categories' => 'json',
];
public function productCategories()
{
return $this->belongsToJson(Category::class, 'Categories');
}
}
class Category extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
}
Be aware that the values of the Categories
column need to be integers, not strings: [1,4]
instead of ["1","4"]
Thanks :)
It has to be ["1.4"] . So the values are string. What can we do?
class Category extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
// What method will be here
}
in the blade
$query->productCategories->CategoryName;
Will it be this way?
It has to be ["1.4"] . So the values are string. What can we do?
Did you test the relationship? Some of the package's features might also work with different data types (integers vs. strings).
BelongsToJson is not working for multiple string values in the categories columns. it is picking one records only.
Probably it needs belongsToManyJson which is not available in the package.