【问题标题】:Laravel return empty when eager child relationship is empty当渴望的孩子关系为空时,Laravel 返回空
【发布时间】:2021-12-20 23:36:21
【问题描述】:

我正在尝试从表名pos_receipt 中获取数据。它有一个子表,其中包含 receipt_id 的列 pos_receipt 主键。如果子表与父表没有关系,我只想返回空。现在,如果没有关系,它会返回带有空父数组的数据。如果子表中没有关系,它应该返回空数组

这里是查询:

 $options = PosReceipt::with([
                    'transferBranch' => function ($query) {
                        $query->where('branch_id',2);
                    },
                ])
                ->where('receipt_no','LIKE','%'.$filters->keyword.'%')
                ->whereDate('receipt_date','>=', $date1)
                ->whereDate('receipt_date','<=', $date2)
                ->where('type', 'TRN')
                ->limit(20)
                ->offset($request->start)
                ->orderBy('id','DESC')
                ->get();

转移分支关系模型的关系是 //PosReceipt的模型CALSS

public function transferBranch()
{   
    return $this->hasMany(TransferStore::class,'receipt_id');
}

【问题讨论】:

  • 添加您的迁移代码和两个表的模型代码。

标签: laravel eloquent laravel-8


【解决方案1】:

hasMany 方法有 3 个参数。

/**
 * Define a one-to-many relationship.
 *
 * @param  string  $related
 * @param  string|null  $foreignKey
 * @param  string|null  $localKey
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function hasMany($related, $foreignKey = null, $localKey = null)

尝试更改为

 return $this->hasMany(TransferStore::class,'receipt_id','id');

并确保您在模型顶部使用它。

use Illuminate\Database\Eloquent\Relations\HasMany;

【讨论】:

  • 它仍然返回带有空子数组的父数据。我只是想如果孩子是空的,它不应该返回父母的数据,只是想要使用 Eager 使用 store_transfer 表进行 LIKE INNER JOIN 查询。
【解决方案2】:

如果有人需要解决方案

$options = PosReceipt::with([
                'transferBranch'
            ])
            ->whereHas("transferBranch",function($q) use($filters){
                $q->where("branch_id","=",$filters->storeID);
            })

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 2019-06-19
    • 2018-09-23
    • 2014-02-24
    • 1970-01-01
    • 2021-06-04
    • 2019-06-04
    • 2014-11-23
    • 2015-04-18
    相关资源
    最近更新 更多