2016-09-29 80 views
0

我在幼虫中使用hasManythrough关系存在问题。只要后续的使用例如,有文档,它们是:Laravel的问题有很多关系

countries 
id - integer 
name - string 

users 
id - integer 
country_id - integer 
name - string 

posts 
id - integer 
user_id - integer 
title - string 

这里是我设置的模式

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Country extends Model 
{ 
public function posts() { 

    return $this->hasManyThrough('App\Post', 'App\User', 'user_id', 'country_id', 'id'); 
} 
} 

这里的关系是用户模型

class User extends Authenticatable 
{ 
use Notifiable; 

/** 
* The attributes that are mass assignable. 
* 
* @var array 
*/ 
protected $fillable = [ 
    'name', 'email', 'password', 
]; 

/** 
* The attributes that should be hidden for arrays. 
* 
* @var array 
*/ 
protected $hidden = [ 
    'password', 'remember_token', 
]; 

public function posts() { 
    return $this->hasMany('App\Post'); 
} 

public function country() { 
    return $this->hasOne('App\User'); 
} 
} 

这里是帖子型号

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Post extends Model 
{ 
    public function user() { 

    return $this->belongsTo('App\User'); 
} 
} 

因此,该网站没有详细了解如何通过国家模式提取帖子。使用路由文件,这是我用

Route::get('posts/countries/{id}', function($id) { 

$countries = App\Country::where('id', $id)->get(); 

return $countries->posts; 

}); 

查询它看起来对我来说,我建立关系正确的文档说的方式。用户表上有一个country_id,所以我不确定查询是错误的还是我确实错误地设置了关系。

回答

0

你实际上并没有要求关系,你只是在查看国家的属性。

如果您想提前查询构建器中的帖子,则需要在构建查询时添加with('posts')。 (致电前->get()其执行查询并把它变成一个集合。)

Route::get('posts/countries/{id}', function($id) { 

$country = App\Country::with('posts')->where('id', $id)->first(); 

return $country->posts; 

}); 

或者,如果你想lazyload你可以通过做->posts()这样的要求对全国模型的关系:

Route::get('posts/countries/{id}', function($id) { 

$country = App\Country::with('posts')->where('id', $id)->first(); 

return $country->posts(); 

}); 

注意:在这两种情况下,我将->get()更改为->first()。我假设你只想要返回一个国家的帖子。

->get()执行查询并将相关模型作为集合返回,->first()从查询中获取第一个模型。

0

@尼克拉斯凯文弗兰克

您的解决方案没有为我工作。至少不是完全的,但你在某些方面是对的。我修修补补四周,发现查询像这样工作更好:

Route::get('posts/countries/{id}', function($id) { 

$country = App\Country::where('id', $id)->first(); 

return view('country')->with('country', $country); 
}); 

所以,像你说的,它胆怯所需的 - >第一个()的选项,但它并不需要用(“职位” )部分。但非常感谢我的朋友。没有你,我无法解决这个问题。