mysql - 为什么 Laravel 闭包中 undefined variable ?

标签 mysql laravel laravel-5 query-builder laravel-query-builder

我有两个 3 表:用户、个人资料、friend_request

$my_profile_id变量存储用户个人资料ID的值

$my_user_id = Auth::user()->id;
$my_profile_id =   DB::table('profiles')->select('profiles.profile_id', 'profiles.id')->leftjoin('users','users.id' ,'=' ,'profiles.id')->where('users.id',$my_user_id)->pluck('profiles.profile_id')->first();

$friend_accept = DB::table('friend_request')->select('profiles.profile_id','profiles.first_name','interest_request.sent_at','interest_request.interest_id')->leftjoin('profiles', function($join){
$join->on('interest_request.sender_id' , '=','profiles.profile_id');
$join->orOn('interest_request.to_user_id' , '=','profiles.profile_id');
 })->where('to_user_id',$my_profile_id)->orwhere('sender_id',$my_profile_id)->where('interest_status','2')->whereNotIn('profiles.profile_id', function($q)
  {
   $q->select('profiles.profile_id')->from('profiles')->where('profiles.profile_id',$my_profile_id);
   })->groupby('profiles.profile_id')->get(); 

$my_profile_id 变量在 whereorwhere 子句中工作正常,但是当我在 whereNotIn 子查询中使用时它创建错误的子句:变量未定义

最佳答案

虽然您的代码风格有点难以阅读,但看起来您缺少一个步骤。然而,我喜欢的代码风格已经在回复中写下了可能有效的代码。不要对自己太苛刻,并遵循这种代码风格。

您的代码:

whereNotIn('profiles.profile_id', function($q)
{

发布代码:

whereNotIn('profiles.profile_id', function($q) use ($my_profile_id) {

发生的事情是您错过了有关使用方法的完整说明。

关于mysql - 为什么 Laravel 闭包中 undefined variable ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53300674/

相关文章:

mysql - SELECT 列与 GROUP BY 列不同

php - 如何在 php 中获取和存储菜单值

php - Laravel只搜索7天的记录

php - Laravel - 在数据库中插入新条目时发送电子邮件吗?

php - Laravel php artisan 迁移不工作

laravel - 仅删除单个方法的 csrf token - Laravel

php - Laravel 5 输入旧为空

php - 排除查询数据库

mysql - 有什么办法可以关闭全文搜索的 50% 陷阱吗?

php - 如何查询 all、orderby 和 paginate?