【问题标题】:Larave - how get in array values from pivot tableLaravel - 如何从数据透视表中获取数组值
【发布时间】:2019-07-20 16:22:48
【问题描述】:

我有一个来自用户和课程的表格数据透视表。

今天,当列 end_at 为 > 时,我只需要获取 course_id。

所以,我在用户模型中创建了一个方法来获取这个条件。

public function getPurchasedCoursesId()
{
    return $this->courses()->wherePivot('end_at','>=', Carbon::now())->get();

}

这会正确返回结果,但是如何使结果只返回特定列(course_id) 示例结果:

$course_ids = $user->getPurchasedCoursesId()
dd($coursesids)
Result:
[1, 4, 6, 10]

【问题讨论】:

    标签: laravel pivot


    【解决方案1】:

    最简单的方法是使用pluck()

    $this->courses()->wherePivot('end_at','>=', Carbon::now())->pluck('id');
    

    上面实际上是从courses 表而不是pivot 表中提取信息,因为两者的数据将在同一个查询中检索。

    【讨论】:

    • @Alexd2 很高兴我能帮上忙!
    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2017-05-17
    • 2017-10-16
    • 2021-04-25
    相关资源
    最近更新 更多