简体   繁体   English

Laravel有很多通过关系

[英]Laravel Has Many Through relation

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%'. 在我的情况下,我只想列出像'%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! 如何在帖子模型中定义国家关系?belongsToThrough已经尝试但没有工作。很多人!

The problem that you're facing is that there is no reverse of the "hasManyThrough" relationship, ie there is no such thing as "belongsToThrough". 你面临的问题是“hasManyThrough”关系没有逆转,即没有“belongsToThrough”之类的东西。

You will probably have do to this with an explicit join, eg 您可能会通过显式连接来做到这一点,例如

$query = Post::where('countries.name', 'like', '%' . $param['country'] .'%')
    ->join('users', 'users.id', '=', 'posts.user_id')
    ->join('countries', 'countries.id', '=', 'users.country_id')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM