在模型值及其关系(一对多)中查找字符串的一部分的自定义搜索

Custom search that look for part of a string inside values of a model and its relationship (one to many)

我有一个搜索输入文本,它使用 ajax 来搜索一些文章(文章是模型)。此外,我还与另一个模型“ArticleFile”建立了关系 one-to-many。本质上,我需要查看文章 table 的“标题”或“描述”列中是否有一个值包含字符串,或者在文章文件 [=24] 的文件名列中(这是最难的部分) =] 与列 article_id。由于许多文章都包含一个附加文件列表,是否有一种方法可以搜索文章的标题、描述或附加的文件名是否具有类似于我的代码的特定字符串?或者有其他方法可以实现吗?

我的文章模型中的关系 one-to-many:

public function files() {
   return $this->hasMany(ArticleFile::class);
}

在 ajax 调用的 php 文件中,我有以下方法来检索正确的文章(不起作用):

public function ajax_article_search()
{
  $value = $_POST['value'];
  $html = '';

  if($value) {
    
    // search if the title
    // or description
    // or filenames (of the relationship one-to-many)
    // have a certain $value
    $articles = Article::where('title', 'like', '%'.$value.'%') 
      ->orWhere('description', 'like', '%'.$value.'%') 
      ->files->where('filename', 'like', '%'.$value.'%') 
      ->get(); 
    
    // -- Code above not working
    // Error because of ->files...
        
    foreach($articles as $article) {
      $html .= '<a href="'.$article->url.'">';
      $html .= '<p>'.$article->title.'</p>';
      $html .= '</a>';
    }
  }

  echo $html;
}

要查询关系,您可以使用 whereHas()(或在本例中为 orWhereHas()):

$articles = Article::where('title', 'like', '%'.$value.'%')
    ->orWhere('description', 'like', '%'.$value.'%')
    ->orWhereHas('files', function ($query) use($value) {
        $query->where('filename', 'like', '%'.$value.'%');
    })
    ->get();