Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 很好,我如何在其他模型关系函数中调用关系函数_Laravel_Eloquent_Laravel 5.3 - Fatal编程技术网

Laravel 很好,我如何在其他模型关系函数中调用关系函数

Laravel 很好,我如何在其他模型关系函数中调用关系函数,laravel,eloquent,laravel-5.3,Laravel,Eloquent,Laravel 5.3,我在雄辩方面有个问题,你们可以从标题中读到。我有一个基础和用户模型。所有的模型都需要与基础相关。我不想为每个模型创建一个数据透视表,所以我想在其他模型的基础关系函数中调用用户模型的基础关系函数。您可以阅读示例代码: class User extends Model{ public function foundations(){ return $this->belongsToMany(Foundation::class); } } class Personnel

我在雄辩方面有个问题,你们可以从标题中读到。我有一个基础和用户模型。所有的模型都需要与基础相关。我不想为每个模型创建一个数据透视表,所以我想在其他模型的基础关系函数中调用用户模型的基础关系函数。您可以阅读示例代码:

class User extends Model{

   public function foundations(){
      return $this->belongsToMany(Foundation::class);
   }

}

class Personnel extends Model{

  public function user(){
    return $this->belongsTo(User::class);
  }

   public function foundations(){
      return $this->user->foundations();
   }

}
当我跑的时候

Personnel::with("foundations")->first();
此代码返回错误的基础

**Edit 1=在datatable I中,使用foundations()函数检索数据。所以我必须像这样使用=>{Model}->foundations()

Personnel::with('user.foundations')->first()
句点表示您也要急于加载关系。

试试这个

Personnel::with("user.foundations")->first();

在人员模型中不需要
foundations()

我在同一个函数上使用动态模型,所以我必须使用foundations()关系函数。我编辑了这个问题,我不明白你的意思。你能展示控制器吗,或者在你使用它的任何地方?如果您像这样加载它(我的答案),您可以得到这样的用户:
$user=$personals->user
您可以获得如下基础:
$foundations=$personal->user->foundations
,假设您将查询结果存储在
$personal
变量中。我获得动态模型的数据如下:$this->eloquentModel->whereHas('foundations',function($table){return$table->where('slug',$this->foundationSlug);});$this->eloquentModel意味着一个模型。所以这个函数是动态的,我需要所有模型中的foundations函数。很高兴同意。是的,你理解正确。谢谢你的回答。愿原力与你同在@devkMay原力与你同在@devk;)我在同一个函数上使用动态模型,所以我必须使用foundations()关系函数。我编辑这个问题。