簡體   English   中英

Laravel有很多通過關系

[英]Laravel Has Many Through relation

那是我的桌子:

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

在我的情況下,我只想列出像'%keyword%'這樣的國家/地區的帖子。 我已經定義了國家模型:

<?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');
    }
}?>

現在,用戶將輸入國家名稱或帖子標題關鍵字來搜索帖子。我的控制器:

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'] . '%');
        });
    }   
}

如何在帖子模型中定義國家關系?belongsToThrough已經嘗試但沒有工作。很多人!

你面臨的問題是“hasManyThrough”關系沒有逆轉,即沒有“belongsToThrough”之類的東西。

您可能會通過顯式連接來做到這一點,例如

$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