php - Laravel 函数中无法识别变量

标签 php mysql database laravel

这是我的代码:

public function userprofile($id)
{
    $users = DB::table('users')->where('username', $id)->get();

    $myposts = DB::table('posts')->where('maker', $id)->get();

    $user_id = $id;

    $postsvotes = DB::table('posts')
    ->join('upvotes', function($join)
    {
        $join->on('post_id', '=', 'upvotes.post_id')
             ->where('upvotes.user_id', $user_id);
    })
    ->get();

    return View::make('users.profile')->with('users', $users)->with('myposts', $myposts)->with('myvotes', $postsvotes);
}

我正在使用连接,正如您在其中看到的那样,我有这个变量 $user_id ,这应该是您从函数 userprofile($id) 中作为参数获得的 $id 但我似乎看不到将该参数放入 where 子句中。

问候,

最佳答案

继续尝试(注意use ($user_id)部分):

->join('upvotes', function($join) use ($user_id)
{
    $join->on('post_id', '=', 'upvotes.post_id')
         ->where('upvotes.user_id', $user_id);
})

这可能是一个变量范围问题。请参阅 http://php.net/manual/en/functions.anonymous.php 中的示例 #3 闭包和范围界定

关于php - Laravel 函数中无法识别变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26702343/

相关文章:

php - Laravel firstOrNew 具有多个条件?

安卓数据库索引

PHP MYSQL while 循环直到与 break 和 sum 相同的值,而不是与下一个值相同

php - 将来自另一个表的每行作为数组连接起来

php Mysql 多个WHERE的时候如何标记origin?

C# 登录页面。 SQL 数据库路径

c++ - 如何使用 Poco::Data 获取多个结果集?

php - 根据数据库记录检查 NULL -> isset 与 is_null

php - 我尝试将其转换为与 Laravel 的 DB 类一起使用,但它没有返回任何内容

php - 尝试访问 soap 网络服务器时出现 cURL 错误 58