📜  从子表列进行雄辩的搜索 - 无论代码示例

📅  最后修改于: 2022-03-11 14:59:32.007000             🧑  作者: Mango

代码示例2
$fields = array('membership' => ['expiration'], 'firstname', 'middlename', 'lastname', 'email', 'dlnumber', 'membership_id');

// orWhereHas will use joins, so we'll start with fields foreach
foreach ($fields as $relation => $field)
{
  if (is_array($field))
  {
    // here we join table for each relation
    $query->orWhereHas($relation, function ($q) use ($field, $search) {

      // here we need to use nested where like: ... WHERE key = fk AND (x LIKE y OR z LIKE y)
      $q->where(function ($q) use ($field, $search) {
        foreach ($field as $relatedField)
        {
          foreach ($search as $term)
          {
            $q->orWhere($relatedField, 'like', "%{$term}%");
          } 
        } 
      });
    });
  } 
  else
  {
    foreach ($search as $term)
    {
      $query->orWhere($field, 'like', "%{$term}%"); 
    } 
  } 
}