laravel-scout-tntsearch-driver icon indicating copy to clipboard operation
laravel-scout-tntsearch-driver copied to clipboard

TNT indexing command fails with "Trying to get property of non-object"

Open michaelklopf opened this issue 7 years ago • 2 comments

Hi everyone,

I'm partially sure this worked before, but I get problems while indexing my model with php artisan tntsearch:import App\\Department.

Here is the toSearchableArray method:

    public function toSearchableArray()
    {
        $array = $this->toArray();

        $employees = $this->employees()->get()->map( function ($employee) {
            return $employee->full_name;
        });

        $array['employees'] = implode(' ', $employees->toArray());
        
        $array['company'] = $this->company()->get()->first()->name;

        $array['ngrams'] = utf8_encode((new TNTIndexer)->buildTrigrams($this->name));

        return $array;
    }

$this here is not containing any attributes. This results in $this->company() being null. Hence the error Trying to get property 'name' of non-object.

Creating the index with php artisan scout:import App\\Department works and $this is filled with all attributes.

Any idea how to understand why one is working and the other is not? Can I ignore it or does it need to be fixed?

michaelklopf avatar Jun 12 '18 08:06 michaelklopf

It seems like one of your models doesn't have a company assigned to it. What you should do is a simple check

    if($company = $this->company()->get()->first()) {
        $array['company'] = $company->name;
    }

nticaric avatar Jun 12 '18 10:06 nticaric

Well, the issue is that $this itself has nothing applied to it. scout:import gets an entry from the database on $this for each run through toSearchableArray but tntsearch:import does not.

michaelklopf avatar Jun 13 '18 07:06 michaelklopf