【发布时间】:2016-10-12 15:53:04
【问题描述】:
我想编写一个基于可选条件的查询,该条件将从不同的表中获取数据。我的架构看起来像
myboxes 表
id,
type_id --> foreign key to box_type table
postal_code
po_box
created_at
updated_at
mybox_access 表
id
mybox_id -> foreign key to myboxes table
email
box_type 表
id
type_name
这是我的模型 MyBox.php
class MyBox extends Model {
public function type() {
return this->hasOne(BoxType::class, 'id', 'type_id');
}
public function access() id
return this->hasOne(MyBoxAccess::class, 'mybox_id', 'type_id');
}
}
MyBoxType.php 有如下关系
public function mybox() {
return this->hasOne(MyBox::class, 'id', 'type_id');
}
和MyBoxAccess.php有如下关系
public function vbox() {
return $this->belongsTo(MyBox::class, 'id', 'mybox_id');
}
现在我想根据以下条件得到 我将电子邮件作为必需参数,将 postal_code 和 po_box 作为可选参数(但其中一个是必须的,并且两者都可以存在)。
所以我想获取 type_id 为 3 的所有 my_boxes 的数据,或者 mybox_access 表中与电子邮件匹配的所有 myboxes 的数据,并且 postal_code 或 po_box 与 myboxes 表中的参数匹配
对于 params 邮政编码和 po_box 的简单匹配,我可以写一些类似的东西
$result = new MyBox();
if(!empty($request['postal_code'])) {
$result->where('postal_code', like, '%'.$request['postal_code']);
}
if(!empty($request['po_box'])) {
$result->where('po_box', like, '%'.$request['po_box']);
}
$result = $result->get();
但我不知道如何获取上述条件的数据。当我尝试使用with() 时,就像
MyBox::with(['access' => function(Builder $query) use ($request){
$query->where('mybox_id',$request['id']);
}])->get();
我明白了
`Argument 1 Passed to {closure} () must be an instance of Illuminat\Database\Query\Builder, instance of Illuminate\Databaase\Eloquent\Relation\HasOne given`
任何机构都可以告诉我如何根据上述条件获取数据
【问题讨论】: