【问题标题】:fetching data from three tables in laravel从 laravel 中的三个表中获取数据
【发布时间】:2018-09-27 06:12:16
【问题描述】:

是表结构,基本有三张表,分别是费用、类别和sunbcategories

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

这是需要的 SQL 查询

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);

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

function fetchExpenseData($categoryId)
{
    $expense = Expense::select("expenses.*","categories.category_name as 
    Categoryname","subcategories.Sub_category_name")
        ->join("categories","categories.id","=","expenses.category_id");
        ->join("subcategories",function($join)
        {
            $join>on("subcategories.category_id","=","expenses.category_id")
                ->on("suncategories.id","=","expenses.sub_category_id")
        })->get();
    return $expenses;
}

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

提前致谢

【问题讨论】:

  • $join>on( 上的错字,更新它,如果您仍然没有得到 o/p,请告诉我们
  • 还是没有得到数据,是查询错误
  • 你知道你的 Laravel 代码中有一个 extra 连接条件,而原始 MySQL 查询没有这个条件吗?您真的想在这里使用哪个版本的查询?
  • 你的sql没有$join->on("subcategories.category_id","=", "expenses.category_id")这个条件,你也没用过$categoryId
  • Jigar,我能知道替代方案吗

标签: mysql laravel


【解决方案1】:
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

【讨论】:

  • 感谢您的帮助,在这种情况下打印格式是否相同,您是否知道如何根据特定 ID 获取它
  • 是的,格式不太一样,但组织得很好,而不是 sql 中的查询生成器
猜你喜欢
  • 2020-09-01
  • 1970-01-01
  • 2017-07-08
  • 2016-06-24
  • 2018-10-03
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
相关资源
最近更新 更多