gpt4 book ai didi

php - 在同一 Controller 中的几个方法中重用 mysql 查询代码 - Laravel 5.4

转载 作者:行者123 更新时间:2023-11-29 06:01:43 25 4
gpt4 key购买 nike

我想将它用于同一个 Controller 中的几个方法的查询很少。例如下面的代码:

$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');

我需要在 UserController 的 4 个方法中调用上面的查询。

我想做这样的事情:

public function john_doe()
{
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}

然后

UserController

public abc (){john_doe();}
public def (){john_doe();}
public ghi (){john_doe();}
public jkl (){john_doe();}

但是我得到一个错误。当我在一个地方更改代码时它会反射(reflect)到所有地方,我该怎么做?

更新问题

public function notify()
{
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$friends = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
$notifications = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');

}

public function index()
{

$this->notify();
return view('/users/index',compact('send_requests','accept_rejects','sent_requests','users','bio','photo','friends','status','seeks','filters','notifications'));
}

最佳答案

那是一段写得不好的代码。除了来自已登录用户模型的通知之外,您可以获得所有内容。

public function fetchData()
{
$user = auth()->user();
$notifications = Notification::where('created_at', '>' , $user->lastlogin)->get();

$data = [
'lastlogin' => $user->lastlogin,
'bio' => $user->bio,
'photo' => $user->photo,
'search_status' => $user->search_status,
'notifications' => $notifications,
];

return (Object)$data;
}

public function test()
{
$data = $this->fetchData();

// $data->lastlogin;
// $data->bio;
// $data->photo;
// $data->search_status;
// $data->notifications;
}

关于php - 在同一 Controller 中的几个方法中重用 mysql 查询代码 - Laravel 5.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44389644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com