简体   繁体   中英

Laravel eloquent relation for nested select query of mysql

I am stuck in the middle of nowhere in Laravel Eloquent relation for nested select query of MySQL . My query goes this way.

SELECT
  *,
  GROUP_CONCAT(p.facility) AS facility
FROM
  (SELECT
    `proposals`.*,
    `proposals`.`desc` AS `pending`,
    `proposals`.`Date` AS `date`,
    `pl`.`type` AS `facility`,
    `ps`.`id` AS `proposalStatusId`,
    `ps`.`status` AS `proposalStatus`
  FROM
    `proposals`
    INNER JOIN
      (SELECT
        *
      FROM
        (SELECT
          *
        FROM
          `proposal_status`
        ORDER BY `created_at` DESC) AS ps
      GROUP BY `ps`.`proposalId`
      HAVING ps.status BETWEEN 4.2
        AND 4.3) AS ps
      ON `proposals`.`id` = `ps`.`proposalId`
    INNER JOIN `proposal_long` AS `pl`
      ON `proposals`.`id` = `pl`.`proposalId`
  WHERE `proposals`.`desc` <> ''
  HAVING `proposals`.`status` = 1) AS p

This query works fine when I use in DB::select() and outputs the desired result. But doesn't work when eloquent relation is implemented which is as follow.

$proposals = Proposals::having('status', DMS::PUBLISH);

$proposalsStatusRaw = proposalStatus::orderBy('created_at', 'desc');

$proposalsStatus = DB::table(DB::raw('(' . $proposalsStatusRaw->toSql() . ') AS ps'))
    ->groupBy('ps.proposalId')
    ->havingRaw('ps.status between ' . DMS::STEP_5 . ' and ' . DMS::STEP_6);

$proposalsRaw = $proposals->select('proposals.*', 'proposals.desc as pending', 'proposals.Date as date', 'pl.type AS facility', 'ps.id AS proposalStatusId', 'ps.status AS proposalStatus')
    ->join(DB::raw('(' . $proposalsStatus->toSql() . ') AS ps'), function ($query) {
        $query->on('proposals.id', '=', 'ps.proposalId');
    })
    ->join('proposal_long AS pl', function ($query) {
        $query->on('proposals.id', '=', 'pl.proposalId');
    })
    ->where('proposals.desc', '<>', '');

$proposals = DB::table(DB::raw('(' . $proposalsRaw->toSql() . ') AS p'))
    ->select('p.*', DB::raw('GROUP_CONCAT(p.facility) AS facility'));

This relation outputs the same query as previously mentioned but results the null value. Please help me fix the error in this.

Replace $proposalsStatusRaw = proposalStatus::orderBy('created_at', 'desc'); to $proposalsStatusRaw = proposalStatus::all()->orderBy('created_at', 'desc');

Try to dump $proposalStatusRaw by adding this dd($proposalStausRaw) and let see if any result returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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