Laravel 5 如何在Laravel 5控制器中检索hasManyThrough

Laravel 5 如何在Laravel 5控制器中检索hasManyThrough,laravel-5,Laravel 5,我有一个设置,空间有帖子,帖子可能有链接。我需要过滤掉属于私人空间的链接。Links表没有space_id列,所以我的理解是hasMany-through可以通过posts表获取属于某个空间的链接 我在谷歌上搜索了这个,阅读了文档,并按照这里的建议链接,但是找不到任何能给我指路的东西 我在最近的尝试中也遇到了一个错误 Undefined property: Illuminate\Database\Eloquent\Collection::$links Space.php public func

我有一个设置,空间有帖子,帖子可能有链接。我需要过滤掉属于私人空间的链接。Links表没有space_id列,所以我的理解是hasMany-through可以通过posts表获取属于某个空间的链接

我在谷歌上搜索了这个,阅读了文档,并按照这里的建议链接,但是找不到任何能给我指路的东西

我在最近的尝试中也遇到了一个错误

Undefined property: Illuminate\Database\Eloquent\Collection::$links
Space.php

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

/** 
* A Space can have links through posts.
*
* The first argument passed to the hasManyThrough method is the name of the final model we wish to access
* The second argument is the name of the intermediate model
*
* The third argument is the name of the foreign key on the intermediate model
* The fourth argument is the name of the foreign key on the final model
*
*/

public function links() {
  return $this->hasManyThrough('App\Link', 'App\Post','space_id','post_id');
} 
Post.php

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

/** A Post belongs to a space.
*
*
*/
public function space() {
  return $this->belongsTo('App\Space');
} 
Link.php

public function post() {
    return $this->belongsTo('App\Post');
}
我在links控制器中尝试的是不同的版本

$private = Space::where('spaces.isPublic','=', 0)->get();
$privateLinks = $private->links();
但我一直没能让它工作,我想知道是否有人能告诉我去那里的路

谢谢。

$private->links()
返回一个查询生成器,而不是一组链接。您可以使用
$private->links
(无
()
)来获取链接集合本身,也可以使用查询生成器上的
get()
来检索它们。查询生成器允许您在查询中提供过滤器,如
$private->links()->where('foo','bar')->get()
,但在获得链接之前,必须调用
get()

$private=Space::where('spaces.isPublic','=',0)->get()
还返回一组空格

您可以执行类似于
$private[0]->links的操作
或将其更改为
$private=Space::where('spaces.isPublic','=',0)->first()
以仅获取第一个私有空间,或者您可以遍历所有私有空间并使用它们的链接执行以下操作:

foreach($private as $pr){ 
    $links = $pr->links;
    //dosomething
}

因此,它在logs-Undefined属性:illumb\Database\Eloquent\Collection::$links中给了我这个错误,这是否意味着模型关闭了?