如何在嵌套查询Laravel中使用父数据库表的字段

时间:2019-04-04 11:25:54

标签: laravel eloquent nested-query

所以我有以下问题,我想将父级的表字段用于子查询或嵌套查询中

让我们说我的表结构和数据是:: sql schema here

CREATE TABLE `table_test` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `user_id` INT(11) NULL DEFAULT '0',
    `effective_date` DATETIME NULL DEFAULT NULL,
    PRIMARY KEY (`id`)
)
ENGINE=InnoDB
;

INSERT INTO `table_test` (`id`, `user_id`, `effective_date`) VALUES
    (1, 1, '2019-01-04 16:03:21'),
    (2, 1, '2019-02-04 16:03:21'),
    (3, 1, '2019-03-04 16:03:21'),
    (4, 1, '2019-04-04 16:03:21'),
    (5, 1, '2019-05-04 16:03:21'),
    (6, 2, '2019-01-04 16:03:21'),
    (7, 2, '2019-03-04 16:03:21'),
    (8, 3, '2019-01-04 16:03:21'),
    (9, 3, '2019-03-04 16:03:21');

我的mysql查询是

select * from `table_test`
where effective_date = (
select subtable.effective_date from `table_test` as subtable
  where subtable.user_id = `table_test`.user_id 
  and subtable.effective_date <= now()
  order by subtable.effective_date desc limit 1
);

我想要的是:我们只需要每个用户的最新数据/记录,其中有效日期为laravel中的<=今天日期

我在控制器中的代码是 在控制器中:

$table : TableTest::query()
$table = $table->effectivedate()->get();

和模型

    function scopeEffectivedate($query) {
    $current_date = Carbon::now()->toDateTimeString();
    return $query->where('effective_date',function($query) use($current_date) {
               $query->select('table_alias.effective_date')

                   ->from('table_test as table_alias')
                    ->whereColumn('table_alias.user_id','table_test.user_id')

                   ->where('table_alias.effective_date','<=',$current_date)
                   ->orderBy('table_alias.effective_date', 'DESC')->first();
           });

我的Laravel Framework版本是5.7.28 错误,我正在追求的是

“ where子句”中的未知列“ table_test.user_id”

0 个答案:

没有答案