【问题标题】:Issues with Laravel hasManyThrough relationshipLaravel hasManyThrough 关系的问题
【发布时间】:2017-02-07 20:23:17
【问题描述】:

我在 larval 中使用 hasManythrough 关系时遇到问题。只需按照文档使用那里的示例,它们是:

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;

});

在我看来,我按照文档所说的方式正确地建立了关系。 users 表上有一个 country_id,所以我不确定查询是否错误,或者我确实设置了不正确的关系。

【问题讨论】:

    标签: laravel relationships


    【解决方案1】:

    您实际上并没有请求关系,您只是查看国家/地区的属性。

    如果您想在查询构建器中快速加载帖子,您需要在构建查询时添加with('posts')。 (在您调用 -&gt;get() 之前,它会执行查询并将其转换为集合。)

    Route::get('posts/countries/{id}', function($id) {
    
    $country = App\Country::with('posts')->where('id', $id)->first();
    
    return $country->posts;
    
    });
    

    或者,如果你想延迟加载,你可以通过 -&gt;posts() 来请求国家模型上的关系,如下所示:

    Route::get('posts/countries/{id}', function($id) {
    
    $country = App\Country::with('posts')->where('id', $id)->first();
    
    return $country->posts();
    
    });
    

    注意:在这两种情况下,我都将 -&gt;get() 更改为 -&gt;first()。我假设您只希望返回一个国家/地区的帖子。

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

    【讨论】:

      【解决方案2】:

      @尼克拉斯·凯文·弗兰克

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

      Route::get('posts/countries/{id}', function($id) {
      
      $country = App\Country::where('id', $id)->first();
      
      return view('country')->with('country', $country);
      });
      

      所以,就像你说的,它非常需要 ->first() 选项,但它不需要 with('posts') 部分。但是非常感谢我的朋友。没有你,我无法解决这个问题。

      【讨论】:

        猜你喜欢
        • 2018-07-24
        • 2018-10-18
        • 2023-03-09
        • 1970-01-01
        • 2020-10-14
        • 1970-01-01
        • 1970-01-01
        • 2018-03-08
        • 2021-12-06
        相关资源
        最近更新 更多