在`WITH`方法中使用当前Eloquent的变量 - LARAVEL

时间:2017-08-21 01:51:38

标签: laravel laravel-5

所以我有这个代码(不起作用):

$accessuser = AccessUser::where('user_id', Auth::user()->id)
              ->with(['overtimes' => function ($qry) use ($accessuser) {
                  $qry->where('waiting_for', $accessuser->access_level)->get();
              }])->get();

显然,我只想获取access_level列的值,并将其与waiting_for列进行比较。

这有什么解决方案吗?如果您需要有关我的表结构等的任何其他信息,请告诉我。

EDITED

这是我的AccesschartUserMap模型:

Schema::create('accesschart_user_maps', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('accesschart_id')->unsigned();
    $table->integer('user_id')->unsigned()->nullable();
    $table->integer('access_level')->unsigned()->nullable();
    $table->timestamps();

    $table->foreign('user_id')
        ->references('id')->on('users')
        ->onDelete('cascade');

    $table->foreign('accesschart_id')
        ->references('id')->on('access_charts')
        ->onDelete('cascade');
});

我的Overtime型号:

Schema::create('overtimes', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->integer('accesschart_id')->unsigned()->nullable();
    $table->integer('remarks_by')->unsigned()->nullable();
    $table->integer('waiting_for')->nullable();
    $table->datetime('date_from');
    $table->datetime('date_to');
    $table->longtext('reason');
    $table->longtext('remarks')->nullable();
    $table->integer('status')->nullable();
    $table->timestamps();

    $table->foreign('user_id')
        ->references('id')->on('users')
        ->onDelete('cascade');

    $table->foreign('remarks_by')
        ->references('id')->on('users')
        ->onDelete('cascade');
});

这是我想要实现的查询:

SELECT accessuser.user_id,accessuser.accesschart_id,accessuser.access_level,overtimes.waiting_for
FROM accesschart_user_maps as accessuser
INNER JOIN overtimes ON accessuser.accesschart_id = overtimes.id
WHERE accessuser.user_id = 7 and accessuser.access_level=overtimes.waiting_for

2 个答案:

答案 0 :(得分:0)

我认为这是"查询构建器"您要实现的查询的版本。

$accessuser = DB::table('accesschart_user_maps as accessuser')
->join('overtimes', 'accessuser.accesschart_id', '=', 'overtimes.id')
->select('accessuser.user_id','accessuser.accesschart_id','accessuser.access_level','overtimes.waiting_for')
->where('accessuser.user_id', \Auth::User()->id)
->where('accessuser.access_level', 'overtimes.waiting_for')
->get();

希望有所帮助

答案 1 :(得分:0)

我想你应该试试这个:

$accessuser = DB::table('accesschart_user_maps as accessuser')
->select('accessuser.user_id as user_id','accessuser.accesschart_id as accesschart_id','accessuser.access_level as access_level','overtimes.waiting_for as waiting_for')
->join('overtimes','overtimes.id','=','accessuser.accesschart_id')
->where('accessuser.user_id','=',7)
->where('accessuser.access_level','=','overtimes.waiting_for')
->get();

希望这对你有用!!!