I have two models in which I need to relate to, a Users
model and a Prices
model. In my Prices
model there is a JSON object
which holds an ID
of a user and I was wondering if I could relate to my Prices
table using the ID
which is in the Prices
model?
I know you could use an getAttribute
and then return the user like that, but I was wondering if there is a $this->hasOne()
method you could use?
e.g.
JSON
{user_id: 1, other_values:"in the object"}
Prices Model
class Prices extends Model {
/* Prices has the column 'object' which has the JSON object above */
protected $casts = ['object' => 'array'];
public function user(){
return $this->hasOne("App\User", $this->object->user_id, "id"); /* ! Example ! */
}
}
I created a package with JSON relationships: https://github.com/staudenmeir/eloquent-json-relations
Since the foreign key is in the Prices
model, you should use a BelongsTo
relationship:
class Prices extends Model {
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = ['object' => 'array'];
public function user() {
return $this->belongsTo(User::class, 'object->user_id');
}
}
class User extends Model {
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function prices() {
return $this->hasMany(Prices::class, 'object->user_id');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With