我有一个非常简单的一对多多态关系如下。
posts
id - integer
title - string
videos
id - integer
title - string
comments
id - integer
body - text
commentable_id - integer
commentable_type - string
下面是模型中的关系的样子:
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
class Video extends Model
{
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
我使用 Laravel Backpack CRUD 来管理comments
. 在CommentCrudController::setup()
函数中,我添加如下列:
public function setup() {
// Standard CrudPanel Basic Information goes here...
$this->crud->addColumn([
'name' => 'body',
'label' => 'Comment',
]);
$this->crud->addColumn([
'label' => "Related Entity",
'type' => "select", // Need to use type 'select' for property of related model.
'name' => 'commentable_id ',
'entity' => 'commentable', // Function name, defining the polymorphic relationship.
'attribute' => "title", // The column name of the related database table.
]);
}
通过函数中的上述配置CommentCrudController::setup()
,我可以正常得到一个评论概览表。但是,当我尝试使用 Backpack 搜索表单搜索内容时,出现以下错误:
{
message: "Please use whereHasMorph() for MorphTo relationships."
trace: [
{file: vendor/backpack/crud/src/PanelTraits/Search.php", line: 91}
]
}
我确实理解,因为它是与函数的One-To-Many
多态关系,并且在我用来添加as 列的函数中,尝试搜索记录时会尝试在函数内执行以下查询:morphTo()
CommentCrudController::setup()
'type' => "select"
title
"Related Entity"
Laravel Backpack
trait Search::applySearchLogicForColumn()
if ($column['tableColumn']) {
switch ($columnType) {
// Skipped other cases here...
case 'select':
case 'select_multiple':
$query->orWhereHas($column['entity'], function ($q) use ($column, $searchTerm) {
$q->where($column['attribute'], 'like', '%'.$searchTerm.'%');
});
break;
// Skipped default case here...
}
正如错误所说,$query->orWhereHas()
应该改为$query->whereHasMorph()
. 但改变这一点并不能解决问题。而且我还希望能够在title
相关模型的列中进行搜索。
我怎样才能解决这个问题?