laravel中多对多关系时拉出具体数据
Pull out the specific data when the relation ship is many to many in laravel
我想问一下如何从Laravel数据库
中拉出具体的数据(部分列)
这是我的代码:
用户模型:
public function events(){
return $this->belongsToMany('App\Events')->withTimestamps();
}
事件控制器:
public function showjson(){
$user_id=Auth::user()->id;
$events = DB::table('events')
->select(
'id',
'calendar_title as title',
'startdate as start',
'enddate as end',
'calendar_color as backgroundColor',
'calendar_color as borderColor')
->where('user_id',$user_id)
->get();
$user=Auth::user();
$eventData=$user->events;
return $eventData;
}
我已经知道这两者的关系了,我可以通过这个获取数据:
$user = Auth::user();
$eventData = $user->events;
但我想按名称获取特定列,如上面的 select code
。
这是我可以调用特定数据并更改列名称的另一种方式吗?
i want display in json only the calendar_title, calendar_des only.
您可以使用 lists
检索列值列表,查看数据库查询生成器 Retrieving Results section :
$user->events->lists('calendar_title','calendar_des');
如果你想 return Json 格式你可以使用 toJson() method :
$user->events->lists('calendar_title','calendar_des')->toJson();
希望这对您有所帮助。
我想问一下如何从Laravel数据库
中拉出具体的数据(部分列)这是我的代码:
用户模型:
public function events(){
return $this->belongsToMany('App\Events')->withTimestamps();
}
事件控制器:
public function showjson(){
$user_id=Auth::user()->id;
$events = DB::table('events')
->select(
'id',
'calendar_title as title',
'startdate as start',
'enddate as end',
'calendar_color as backgroundColor',
'calendar_color as borderColor')
->where('user_id',$user_id)
->get();
$user=Auth::user();
$eventData=$user->events;
return $eventData;
}
我已经知道这两者的关系了,我可以通过这个获取数据:
$user = Auth::user();
$eventData = $user->events;
但我想按名称获取特定列,如上面的 select code
。
这是我可以调用特定数据并更改列名称的另一种方式吗?
i want display in json only the calendar_title, calendar_des only.
您可以使用 lists
检索列值列表,查看数据库查询生成器 Retrieving Results section :
$user->events->lists('calendar_title','calendar_des');
如果你想 return Json 格式你可以使用 toJson() method :
$user->events->lists('calendar_title','calendar_des')->toJson();
希望这对您有所帮助。