命名空间应用程序;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;
class Event extends Model
{
protected $table = 'events';
public $timestamps = true;
use Searchable;
use SoftDeletes;
protected $dates = ['deleted_at'];
public function entities()
{
return $this->belongsTo('App\Entity', 'entity_id');
}
public function users()
{
return $this->belongsTo('App\User', 'id');
}
public function events()
{
return $this->belongsTo('App\DirtyEvent', 'id');
}
public function toSearchableArray()
{
$data = $this->toArray();
$data['entities'] = $this->entities->toArray();
return $data;
}
}
这是我的 Event 模型,如您所见,我正在使用 toSearchableArray ,它是 Laravel 侦察功能将“关系”导入到 algolia。然而问题是有时它是空的。所以例如
事件 id 1 具有 entity_id 1
但在另一个例子中
事件 id 2 有 entity_id = null
如何修改此函数以在将实体()关系放入数组之前检查它是否不为空?