jeudi 7 janvier 2016

PHP - Eloquence Searchable search on multiple tables no results

I am trying to build a search on my website (using the laravel 5.1 framework). I need to search multiple tables at once. Basically most of the information to search is in the profiles table. But I need to get the email field from the users table (foreign keys: users.user_id & profiles.user_id).

I am using the eloquence library from jarektkaczyk/eloquence and in the wiki, the following code works for searching on multiple tables:

// fulltext search on multiple tables (joined automatically using dot nested relations)
>>> User::search('foo bar', ['name', 'posts.title', 'posts.categories.name', 'profile.address.city'])->get();

So my code is as follows:

$profiles = Profile::search(['admin@example.com'], ['user.email'])->get();

The models need to be linked obviously and I need to set my $searchableColumns, so in my User model:

protected $searchableColumns = ['email'];

public function profile() {
    return $this->hasOne('App\Profile', 'user_id', 'user_id');
}

And my Profile model:

protected $searchableColumns = [
    'first_name',
    'last_name',
    'date_of_birth',
    'cell_number',
    'physical_address',
    'bio',
    'state',
    'active'
];

public function user() {
    return $this->belongsTo('App\User', 'user_id', 'user_id');
}

When I search only the Profile model with the code, I get the results. But if I try join the users table to get the email, no results are returned (only a empty array).

What could I be doing wrong? The code works just fine for anything if I am trying to search only one table.

// working code
$profiles = Profile::search(['admin@example.com])->get();

// not working code
$profiles = Profile::search(['admin@example.com'], ['user.email'])->get();

I have tried:

  • Swapping relationships between User and Profile making the User model belong to the Profile model.
  • Calling the User model and trying to join the Profile model
  • Joining the User model before calling search
  • Joining the User model after calling search

Thanks in advance



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire