我有桌子名为书籍,想在书籍视图中显示“相关书籍”。
books table
`book_id`
`isbn`
`book_name`
`author_name`
`Date`
`number`
`language`
`Translator`
`abstract`
`picture`
`created_at`
控制器代码
public function actionView($id)
{
$model=$this->findModel($id);
$dataProvider=$this->related($model);
return $this->render('view', [
'model' => $model,
'dataProvider' => $dataProvider,
]);
}
protected function related($model)
{
$query = Books::find();
$query->select('book_id,picture, book_name,author_name,(( author_name LIKE \'%'.$model->author_name.'%\')+( book_name LIKE \'%'.$model->book_name.'%\')) as total')
->orFilterwhere(['or like','author_name' , explode(' ',$model->author_name)])
->orFilterwhere(['or like','book_name' , explode(' ',$model->book_name)])
->orderBy('total')
->limit(25);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
问题:
book_name LIKE \'%'.$model->book_name.'%\'
不接受数组。
像LIKE \'%'.explode(' ',$model->book_name).'%\'
之类的东西
它必须是一个正常工作的数组。
如何在选择条件下使用数组。
或者告诉我一些其他方法来获得最佳匹配结果。
TNX
答案 0 :(得分:0)
首先如果你想要Total,则无需在select
中写入条件$query->select('book_id,picture, book_name,author_name,(book_name+author_name) as total');
$model->author_name
$model->book_name
是数组所以你可以这样做。
protected function related($model)
{
$query = Books::find();
$query->select('book_id,picture, book_name,author_name,(book_name+author_name) as total');
$author_names= explode(' ',$model->author_name);
foreach($author_names as $author_name)
{
$query->orFilterwhere(['like','author_name' , $author_name]);
}
$book_names=explode(' ',$model->book_name);
foreach($book_names as $book_name)
{
$query->orFilterwhere(['like','book_name' , $book_name]);
}
->orderBy('total')
->limit(25);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
}
答案 1 :(得分:0)
您需要使用MySQL match() against()功能(或者如果您使用不同的数据库,则替换)。
{{1}}