【问题标题】:Retrieving data from hasMany Relationship从 hasMany 关系中检索数据
【发布时间】:2023-01-04 22:55:19
【问题描述】:

我想显示来自至少有一个“residente”(子表)的“personas”(父表)的数据,它是一对多的关系,我也想显示那个 residente 的数据。 我试图使用 has() 方法来做到这一点,就像 laravel 文档所说的那样: https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence 但它不起作用。

模型看起来像这样

//in the Persona class

  public function residentes()
    {
        return $this->hasMany(Residente::class);
    }

//in the Residente class

public function persona()
  {
    return $this->belongsTo(Persona::class);
  }


//in the PersonasController

public function index()
    {
        $personas = Persona::has('residentes')->get();

        dd($personas);
           
    }

结果 enter image description here //它没有从“residentes”获取数据

【问题讨论】:

标签: php laravel vue.js eloquent


【解决方案1】:

尝试 :

 public function index()
{
    $personas = Persona::with('residentes')->get();
    dd($personas);
       
}

如果你想使用里面的一些键进行搜索居民您可以使用 whereHas 的关系

Persona::with('residentes')
       ->whereHas('residentes',function($residente){
           return $residente->where('column_name',$value);
         })->get();

还尝试在关系本身参考中提及 local_key 和 foreign_key :https://laravel.com/docs/9.x/eloquent-relationships

return $this->hasMany(Comment::class, 'foreign_key', 'local_key');

【讨论】:

  • 抱歉,我忘了在我的帖子中提到它。我已经尝试使用 with() 方法,结果是这样的:i.postimg.cc/1557CYmt/screenshot.pngresidentes 对象是空的
  • 尝试将本地键和外键添加到 laravel 关系中 return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
猜你喜欢
  • 1970-01-01
  • 2011-03-17
  • 2019-10-17
  • 2016-09-16
  • 2012-04-08
  • 1970-01-01
  • 2019-12-11
  • 2022-07-27
  • 1970-01-01
相关资源
最近更新 更多