简体   繁体   中英

Laravel Relation based on value within an JSON object

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?

eg

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');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM