大佬教程收集整理的这篇文章主要介绍了php-基于JSON对象中的值的Laravel关系,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个模型需要关联,一个用户模型和一个价格模型.在我的Price模型中,有一个JSON对象,该对象包含用户的ID,我想知道是否可以使用Price模型中的ID将自己的价格表与我的价格表关联?
我知道您可以使用getAttribute然后像这样返回用户,但是我想知道是否可以使用$this-> hasOne()方法?
例如
JSON格式
{user_id:1,other_values:“在对象中”}
价格模型
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 ! */
}
}
解决方法:
我创建了一个具有JSON关系的包:https://github.com/staudenmeir/eloquent-json-relations
由于外键在Price模型中,因此您应该使用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');
}
}
以上是大佬教程为你收集整理的php-基于JSON对象中的值的Laravel关系全部内容,希望文章能够帮你解决php-基于JSON对象中的值的Laravel关系所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。