基于 JSON 对象中的值的 Laravel 关系

Con*_*son 5 php laravel

我有两个模型需要关联,一个Users模型和一个Prices模型。在我的Prices模型中有一个JSON object持有ID用户的 ,我想知道我是否可以Prices使用模型中的ID哪个与我的表相关联Prices

我知道你可以使用 angetAttribute然后像这样返回用户,但我想知道是否有$this->hasOne()你可以使用的方法?

例如

JSON

{user_id: 1, other_values:"in the object"}

价格模型

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 ! */
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eir 5

我创建了一个具有 JSON 关系的包:https : //github.com/staudenmeir/eloquent-json-relations

由于外键在Prices模型中,您应该使用BelongsTo关系:

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');
    }
}
Run Code Online (Sandbox Code Playgroud)