laravel - Laravel eloquent 获取当前查询的模型属性
问题描述
我正在尝试为 joindraw 表中的 fortune_code 执行 where 子句,与 product 表中的 lucky_fortune_code 进行比较。我如何访问并进行检查?
Product::where('status', StatusConstant::PT_ENDED_PUBLISHED)
->where('lucky_fortune_code', '<>', '')
->with(['joindraw' => function ($query){
$query->where('fortune_code', $this->lucky_fortune_code)
->with('user');}])->desc()->get();
产品.php
class Product extends Model
{
public function joindraw(){
return $this->hasMany('App\Models\Joindraw');
}
Joindraw.php
class Joindraw extends Model
{
public function product(){
return $this->belongsTo('App\Models\Product', 'product_id');
}
解决方案
你可以做的是加入:
Product::where('status', StatusConstant::PT_ENDED_PUBLISHED)
->where('lucky_fortune_code', '!=', '')
->join('joindraws', 'joindraws.fortune_code', '=', 'products.lucky_fortune_code')->get();
顺便说一句,您也可以省略关系'product_id'
中的第二个参数belongsTo()
,因为此列名称已按约定假定。
此外,查询生成器上没有 desc() 方法。改为使用orderBy('lucky_fortune_code', 'desc')
。
然而,当你必须在 Laravel 中编写连接时,你应该考虑一下你的关系结构,因为可能有问题。
推荐阅读
- ios - 从 iOS 应用程序取消或刷新 AirPrint 作业
- python - HTML 表单数据未发布到 url 但显示在 django 模型中
- c++ - 实现不可复制的 C++ 类
- xcode - 未加载 MacOS 10.14.6 库:@rpath/libIrrXMLd.dylib
- kernel - 在 64 位 Ubuntu 16.04 上使用 make-kpkg 编译 32 位内核失败
- javascript - 建立连接后立即丢失连接 - NodeJS/MYSQL
- snowflake-cloud-data-platform - 将谷歌分析自动化到我的数据仓库中
- excel - 基于 3 个唯一单元格的总和数量?
- javascript - 函数定义中的方括号
- python - GAE:如何在我的应用引擎 main.py 中包含其他类