Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Relation based on value within an JSON object

Tags:

php

laravel

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 ! */
    }
}
like image 774
Connor Simpson Avatar asked Jul 04 '18 09:07

Connor Simpson


1 Answers

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');
    }
}
like image 78
Jonas Staudenmeir Avatar answered Sep 18 '22 09:09

Jonas Staudenmeir