Php 如何建立用户与报表表的关系
我有一个名为reports的表,其中有两列。一个是Php 如何建立用户与报表表的关系,php,sql,json,laravel,relationship,Php,Sql,Json,Laravel,Relationship,我有一个名为reports的表,其中有两列。一个是reported\u post\u id,另一个是reporter\u id。在reporter\u id中,值可以大于1,并且是json。我想在唯一的reported\u post\u id和许多reporter\u id之间建立一种关系,后者已经作为json数据保存在列中 公共功能报告(){ return$this->hasMany('App\Models\Repoters','reported\u post\u id'); } 公共职能记者
reported\u post\u id
,另一个是reporter\u id
。在reporter\u id
中,值可以大于1,并且是json。我想在唯一的reported\u post\u id
和许多reporter\u id
之间建立一种关系,后者已经作为json数据保存在列中
公共功能报告(){
return$this->hasMany('App\Models\Repoters','reported\u post\u id');
}
公共职能记者(){
返回$this->belongsTo('App\Model\reporters','reporter\u id');
}
$column=[\DB::raw(“*”)、\DB::raw(“id为可邮寄的\u id”)、\DB::raw(“报告类型为可邮寄的\u类型”);
$data=Repoters::select($column)->with(“repos”)->orderBy('id','DESC')->paginate(50)->unique(“reported_id”);
我想用reporter\u id
显示reporter\u id的所有数据,你可以使用这个包
安装它:
composer require staudenmeir/eloquent-json-relations:"^1.1"
然后在您的用户
模型(或相关模型)中:
从软件包中:
多对多关系
此包还引入了两种新的关系类型:
BelongsToJson
和HasManyJson
在Laravel5.6.25+上,您可以使用它们实现多对多
与JSON数组的关系
在本例中,User
与
角色
。没有透视表,但外键存储为透视表
JSON字段中的数组(users.options
):
ID数组
默认情况下,关系将数据透视记录存储为ID数组:
class User extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = [
'options' => 'json',
];
public function roles()
{
return $this->belongsToJson('App\Role', 'options->role_ids');
}
}
class Role extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function users()
{
return $this->hasManyJson('App\User', 'options->role_ids');
}
}
一切都很好,但我需要与报告者id和报告者id的关系在同一张表中没有区别one@SajidAli这只是一个例子,如果您想与同一个模型相关,只需更新相关模型和键名称。我已经更新了答案。@SajidAli很乐意帮忙。
class User extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = [
'options' => 'json',
];
public function roles()
{
return $this->belongsToJson('App\Role', 'options->role_ids');
}
}
class Role extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function users()
{
return $this->hasManyJson('App\User', 'options->role_ids');
}
}