如何在Laravel eloquent上的相关表的字段中应用where子句

时间:2018-03-16 03:15:36

标签: php mysql laravel

我有以下查询,我需要在Laravel eloquent中实现:

SELECT Q.quoteid
FROM `tblquote` Q
INNER JOIN tbladdress A ON A.addressid = Q.addressid
INNER JOIN tblquotecompany QC ON QC.quoteid = Q.quoteid
INNER JOIN tblcompany C ON C.companyid = QC.companyid
WHERE 
Q.useremail = 'test@test' or 
(Q.ipaddress = '000.00.00.' and A.zipcode = '00000')

我在laravel中设置了所有关系。

我正在努力实现以下目标:

$this->eloquentQuote->newQuery()
                    ->with(EloquentQuote::RELATION_ADDRESS)
                    ->with(EloquentQuote::RELATION_QUOTE_COMPANIES . '.' . EloquentQuoteCompany::RELATION_COMPANY)
                    ->whereHas(EloquentQuote::RELATION_ADDRESS,
                        function ($query) use ($userEmail, $userIp, $zipCode) {
                            /** @var Builder $query */
                            $query->where([
                                [EloquentQuote::USER_EMAIL, '=', $userEmail],
                            ])
                                ->orWhere([
                                    [EloquentQuote::IP_ADDRESS, '=', $userIp],
                                    [EloquentAddress::ZIP_CODE, '=', $zipCode],
                                ]);
                        })->get();

这个Eloquent查询给出了预期的结果,但花了太多时间。

还有其他方法可以有效地做到这一点吗?

你的帮助受到高度重视。

1 个答案:

答案 0 :(得分:0)

我希望以下代码对您有所帮助

$result = DB::table('tblquote')
    ->join('tbladdress', 'tbladdress.addressid', 'tblquote.addressid')
    ->join('tblquotecompany', 'tblquotecompany.quoteid', 'tblquote.quoteid')
    ->join('tblcompany', 'tblcompany.companyid', 'tblquotecompany.companyid')
    ->where('tblquote.useremail', 'test@test')
    ->orWhere([['tblquote.ipaddress','000.00.00.'], ['tbladdress.zipcode', '00000']])
    ->get();