首页 > 解决方案 > Laravel Scout algolia 非对象

问题描述

我正在使用 laravel 创建一个 crud 应用程序,并使用 scout 和 algolia 来执行搜索功能。但是,当我执行 scout:import "App\Majors" 时,它会引发“尝试获取非对象的属性”错误。下面是我的模型。

class Major extends Model
{
    use Searchable;

    protected $fillable = ['title', 'album', 'lyrics', 'youtube_link'];

    public function toSearchableArray()
    {
        $genres = array_map(function($item) {
            return trim($item);
        }, explode(',', $this->college->genres));

        return array_merge( $this->toArray(), ['college' => $this->college->name, 'photo' => $this->college->photo, 'genres' => $genres]);
    }

    public function college()
    {
        return $this->belongsTo('App\College');
    }
}

标签: phplaravellaravel-5algolialaravel-scout

解决方案


我相信问题出在$this->college. 可能至少有一个模型没有大学设置,你运行:

  1. $this->college->genres
  2. $this->college->name
  3. $这个->大学->照片

它们都会失败,因此您可能应该在这种情况下保护您的代码,例如,而不是:

explode(',', $this->college->genres)

你应该使用:

explode(',', $this->college ? $this->college->genres : '')

推荐阅读