Laravel / Eloquent:在多态表中按值搜索行

MrS*_*les 4 polymorphism relation laravel eloquent

我现在陷入困境,希望有人能帮我。我正在使用多态关系,并且想要在数据库中搜索满足“父”表和“子”表中条件的行。

为了具体说明,举一个小例子。给定以下结构,例如,我想寻找价格为“600”、房间为“3”的房产。有没有办法通过雄辩来做到这一点?



表格

表属性(父级)

  • ID
  • 价格
  • 详细信息类型 [可以是“公寓”或“地块”]
  • 详细信息_id

餐桌公寓(儿童)

  • ID
  • 房间

桌子包裹(儿童)

  • ID
  • ...(没有“房间”栏)



人际关系

类别属性

public function details() {
  return $this->morphTo();
}
Run Code Online (Sandbox Code Playgroud)

课程 公寓 + 地块

public function property() {
  return $this->morphMany('Property', 'details')
}
Run Code Online (Sandbox Code Playgroud)




我尝试过的

很多,真的。但不知何故,我总是做错事或错过一些事。我认为应该有效的解决方案是:

Property::with(array('details' => function($query) {
                  $query->where('rooms', 3);
             }));
Run Code Online (Sandbox Code Playgroud)

或者

Property::with('details')
        ->whereHas('details', function($query) {
            $query->where('rooms', '=', '3');
        });
Run Code Online (Sandbox Code Playgroud)

但在这两种情况下我都会收到以下 FatalError:

Class name must be a valid object or a string
Run Code Online (Sandbox Code Playgroud)



你们中有人已经遇到过类似的问题吗?非常感谢您的任何提示。

Ron*_*hof 5

让我们从您的命名约定开始:

public function detail() // It relates to a single object
{
    return $this->morphTo();
}
Run Code Online (Sandbox Code Playgroud)

public function properties() // It relates to several objects
{
    return $this->morphMany('Property', 'details')
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以这样做:

$properties = Property::whereHas('details', function($q)
{
    $q->where('rooms', '=', '3');
})
->where('price', '=', 600)
->get();
Run Code Online (Sandbox Code Playgroud)

请注意,这永远不会退回包裹,因为包裹中没有房间。