问题
Models Product and Category.
Product model has this custom attribute: getCategoryIdAttribute()
. because the way to get category id is a bit complex.
With that attribute I can define the relationship (Product -> Category):
public function category()
{
return $this->belongsTo(Category::class, 'category_id', 'id');
}
This relationship works fine!
But now on the Category model:
public function products()
{
return $this->hasMany(Product::class, 'category_id', 'id');
}
If I use this relationship it fails on SQL.
Example on tinker:
Product::first()->category; // Works!
Category::first()->products; // Undefined column: 7 ERROR: column products.category_id does not exist
Why when I use the relationship Product -> Category works but Category -> Products doesn't?
来源:https://stackoverflow.com/questions/64483032/laravel-relationship-based-on-custom-attribute-not-working-both-directions