简体   繁体   English

在where子句中使用变量

[英]Using variable in where clause

Right now I have this defined in app/routes.php : 现在我在app / routes.php中定义了这个:

View::share('user_image_count', Items::where('user_id', '=', 1)->count());

It returns the number 9 , just what I want. 它返回数字9 ,正是我想要的。

I would like to make this dynamic so it is based on the user_id of the user that is logged in/authenticated. 我想使其动态化,使其基于已登录/已认证的用户的user_id。

I currently use this in my views: 我目前在自己的观点中使用它:

{{ Auth::user()->user_id }}

How can I adjust my query in routes.php so that it uses the authenticated user's id number? 如何在route.php中调整查询,使其使用经过身份验证的用户的ID号?

Have you tried with the following? 您是否尝试过以下方法?

if (Auth::check())
{
    $user_id     = Auth::user()->user_id;
    $items_count = Items::where('user_id', '=', $user_id)->count();

    View::share('user_image_count', $items_count);
}

I believe it should work. 我相信它应该起作用。

You may try something like this: 您可以尝试如下操作:

View::share('user_image_count', function(){
    return Auth::check() ? 
           Items::where('user_id', '=', Auth::user()->user_id)->count() : '';
});

In your view: 您认为:

{{ $user_image_count() }}

I think you can better do this with an helper class . 我认为您可以通过辅助课程更好地做到这一点。

let's say helper as class 比方说帮手

 class Helper{
   public static function GetUserCount($user_id){

       return View::share('user_image_count', Items::where('user_id',$user_id)->count());

   }

} }

and in you view call this class and pass user_id to it 在您的视图中调用该类并将user_id传递给它

Echo this in view {{Helpers::GetUserCount(Auth::user()->user_id)}}

So this way it would be dynamic for all logined user 因此,这种方式对于所有登录用户而言都是动态的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM