8

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 ! */
    }
}
0

1 Answer 1

16

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');
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Your package are awesome!! But i have a problems with this I have a data json like [{"id":1},{"id":3},{"id":5}] How can I make relations with this?
I struggled whole day to use such nice package. But I am getting the following error: require php ^7.2.5 || ^8.0 -> your php version (7.2; overridden via config.platform, actual: 7.2.5) does not satisfy that requirement.
How can I achieve with array like this: [1, 3, 5]
@ShubhamGupta class Video extends Model { use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships; protected $casts = [ 'package_id'=>'json', ]; public function packages() { return $this->belongsToJson(Package::class,'package_id'); } } class Package extends Model { use HasFactory; use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships; public function videos(){ return $this->hasManyJson(Video::class,'package_id'); } } Where my video table has multiple package ids in "package_id" column like [1,2,3]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.