laravel - 通过属性访问另一个表
问题描述
我在模型中定义了从另一个表中获取数据的属性,但是我没有定义这两个表之间的关系:
租赁请求模型
public function getSecurityDepositEntryAttribute() {
return Rent::where([
['property_id', $this->property_id],
['lease_request_id', $this->id],
['type', 'security_deposit_migration'],
])->orderBy('created_at', 'asc')->first();
}
我现在可以LeaseRequest
使用此属性过滤表吗?我试过这个,但得到BadMethodCallException
:
LeaseRequest::whereHas('security_deposit_entry', function($query) {
$query->whereColumnNotIn('status', ['refund_in_process', 'refunded']);
})->get();
如果这是不可能的,我可以用where
属性中的预定义子句定义这两个表之间的关系吗?
解决方案
不,不可能,您必须使用关系并使用compoships lib:
public function rent() {
return $this->hasOne(Rent::class,['lease_request_id','property_id'],['id','property_id'])
->where('type', 'security_deposit_migration')
->orderBy('created_at', 'asc');
}
['lease_request_id','property_id'] 是外键
['id','property_id'] 是本地键
那么你可以使用 whereHas
推荐阅读
- nginx - nginx反向代理添加请求cookie
- perl - (perl) 终端 (Mac) 如何在 @INC 中找到 LWP...?
- awk - 如何减少文本文件中的所有数组索引?
- android - 如何将firebaseStorage中的图像路径获取到firebaseDatabase
- html - 当我使用不同的类时,我的字体真棒图标不起作用
- javascript - 使用 JQuery 文档准备好罕见的未捕获的 ReferenceError
- r - 从 R ggplot2 中的一列绘制特定类别
- firebase - 如何添加 Firebase 安全规则以检查登录用户的电子邮件是否在列表中
- javascript - 为什么 window.addEventListener('keypress', function(e) 不起作用
- python - Python Flask App - 上传图片并显示