【问题标题】:How to get courses through transactions table Laravel如何通过交易表 Laravel 获取课程
【发布时间】:2014-08-06 10:45:24
【问题描述】:

我想通过事务表获取所有用户的课程。

这是我的数据库结构

课程

id | name | description | price

交易

id | course_id | user_id | name | description | expires

用户

id | username | email    

http://laravel.io/bin/da08n

我尝试过加入,但它多次返回同一个用户。

DB::table('transactions')->join('users', 'transactions.user_id', '=', 'users.id')->join('courses', 'transactions.course_id', '=', 'courses.id')->distinct()->get();

如何使用 Eloquent 或其他方式实现这一点?

【问题讨论】:

  • 你应该建立表之间的关系
  • 我该怎么做,因为我正在学习 laravel(newbie)
  • 我正在写答案,等等
  • @MostafaTalebi 我在等你的回答。

标签: php mysql laravel-4 eloquent


【解决方案1】:

嗯。

您有一个称为事务的表和一个课程表。现在,每笔交易都与一门课程相关。 注意:一张表中的一条记录与另一张表中的另一条记录相关,这称为一对一关系。

在 laravel 中,你可以通过 Model 的关系来实现。

您有一个模型称为“交易”,另一个模型称为“课程”。

例如,您可以使用 Cources::find($myId) 从课程表中获取一条记录。

现在,如果您想通过将交易记录与课程表相关联来获取交易记录,您应该这样做(在 Laravel 中):

在您的翻译模型中定义一个名为 course 的方法:

public function course ()
{
   $this->hasOne("course"); // course is the name of another model which should be related
}

然后你像这样使用它:

$result = Transaction::find($myCourseId)->course();

尽管对于您的情况,您希望通过将表的一条记录与另一表的另一条记录匹配来获得许多记录。嗯:

在事务模型中添加以下方法:

public function Users()
    {
        return $this->hasManyThrough('User', 'Course');
    }

通过上述方法,您应该可以通过基于交易的课程方法获取用户。

更多信息,请访问:

http://laravel.com/docs/eloquent#relationships

【讨论】:

  • 但是就像我在问题中所说的那样:I want to get all users with courses through transaction table. 你告诉我如何获得交易属于课程。
  • 当我使用 hasManyThrough 时,我得到了 Column not found: 1054 Unknown column 'clare_courses.transaction_id' in 'field list' (SQL: select clare_users.*, clare_courses.transaction_id` 来自 clare_users 内部连接 ​​clare_courses on clare_courses.id = @98 987654335@ where clare_courses.transaction_id in (1, 3, 4, 5))`
  • 阅读 Laravel 的文档,看来你需要更改默认的外键和主键。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-23
  • 2023-01-14
  • 2021-08-06
  • 1970-01-01
  • 2022-10-25
  • 1970-01-01
相关资源
最近更新 更多