从Laravel中的三个表中获取数据

时间:2018-09-27 06:12:16

标签: mysql laravel

这是表结构,基本上有三个表,分别是费用,类别和类别

# Unit: microseconds
#       expr      min        lq      mean    median        uq        max neval
# data.table  182.265  200.3405  245.0403  234.0825  264.6605   3137.967  1000
# reshape    1757.575 1840.7240 2180.4957 1938.3335 2011.3895 100429.392  1000
# tidyverse  6173.203 6430.7830 6925.6034 6569.9670 6763.9810  29722.714  1000

这是所需的SQL查询

table expenses
(id,category_id,sub_category_id,date,description,amount)
table categories
(id,category_name)
table subcategories
(id,sub_category_name,category_id)

这是Expense模型中的函数,我通过该函数传递category_id 上面提到的相同查询是用laravel编写的,但我无法 提取数据。

select expense.date, expense.description, expense.amount, 
category.category_name, subcategory.sub_category_name
from expenses as expense,categories as category,subcategories as subcategory
where expense.category_id=category.id and
    category.id=subcategory.category_id);
返回的

$ expenses将打印在blade.php中。 我能知道这是什么错误吗

预先感谢

1 个答案:

答案 0 :(得分:0)

Hye there , 
You need to add eloquent model for retrieving data fromenter code here three tables
Like 
I have School Table , Student Table , Teacher Table
School is relating with both Student and Teacher then we will add relationship
In School Model 
`
public function getStudent(){
  return $this->hasMany('student_id' , App\Student);
}

public function getTeachers(){
  return $this->hasMany('teacher_id' , App\Teacher);
}

In Student table
public function getSchool(){
 return $this->hasOne('school_id' , App\School);
}
`
now call data from student
`
$students = Student::with('getSchool.getTeachers')->get()

This Demonstration for  what I have get from your Question