如何在laravel的索引中获得3个表数据?

问题描述 投票:0回答:2

我有3个表学校,school_Details,评级

**学校**

  • ID
  • 那么
  • 电话
  • 学校
  • 电子邮件
  • 状态

学校细节:

-ID

  • 学校ID
  • 图片
  • 状态

评级:

-ID

  • 学校ID
  • RATING_VALUE
  • 状态

评级和学校详细信息对于一个school_id只有一行。

现在,我如何从schoolController中获取索引中所有3个表的所有详细信息

laravel laravel-5 laravel-5.2 laravel-5.1
2个回答
2
投票

使用Laravel关系。

在学校模型中添加此项。

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

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

在学校详情模型中添加此项。

public function school()
{
    return $this->belongsTo('App\School');
}

在评级模型中添加此项。

public function school()
{
    return $this->belongsTo('App\School');
}

在学校控制器

public function index()
{
   $schools = Schools::with('schoolDetails')
                     ->with(ratings)
                     ->get();
   return $schools;
}

你能试试吗


0
投票

这是一个非常广泛的问题。这将有助于展示你到目前为止所尝试的内容。答案是创建从学校到详细信息和评级的one to many关系。

然后从索引方法中调用基础学校对象中的那些关系。您甚至可以通过eager load从数据库中进行简单而干净的拉动。

从您的学校模型中澄清:

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

你学校的细节也一样。然后,在您的索引方法中急切加载:

$schools= App\School::with(['ratings', 'details'])->get();

那么你的学校对象就是你所要求的:

$school->ratings->status

等等

© www.soinside.com 2019 - 2024. All rights reserved.