Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Has Many Through relation

Tags:

php

laravel

That's my table:

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

In my case I just want to list the posts in the country where like '%keyword%'. I have defined on the country model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
   /**
     * Get all of the posts for the country.
     */
    public function posts()
    {
        return $this->hasManyThrough('App\Post', 'App\User');
    }
}?>

Now,the user will input a country name or a post title keyword to search the posts.My controller:

public function posts()
{
    $param = Input::all();

    if (isset($param['country']) && $param['country']) {
        $query = Posts::whereHas('country', function($q) use ($param) {
            $q->where('name', 'like', '%' . $param['country'] . '%');
        });
    }   
}

How to define country relation in posts model?belongToThrough has tried but not work.Many tks!

like image 997
user4877203 Avatar asked Jan 20 '26 02:01

user4877203


1 Answers

The problem that you're facing is that there is no reverse of the "hasManyThrough" relationship, i.e. there is no such thing as "belongsToThrough".

You will probably have do to this with an explicit join, e.g.

$query = Post::where('countries.name', 'like', '%' . $param['country'] .'%')
    ->join('users', 'users.id', '=', 'posts.user_id')
    ->join('countries', 'countries.id', '=', 'users.country_id')
like image 53
delatbabel Avatar answered Jan 21 '26 16:01

delatbabel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!