select 从一个表中很少,并且基于从另一个表中获取的值

发布时间:2022-10-07 / 作者:清心寡欲

本文介绍了select 从一个表中很少,并且基于从另一个表中获取的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三张桌子:

  • Products
    • id
    • 其他值
  • Downloads
    • id
    • user_id
    • product_id
  • Users
    • id
    • name

我想获取最后 X 下载表行,获取他们的 product_id 和 user_id,product_id 匹配产品表作为 user_id 匹配用户表,然后制作

foreach ($values as $value) {
    <div > {{$product->name}} </div>
    <div > {{$user->name}} </div>
}

我可以通过我的 controller 下载 model,但它并没有让我靠近

public function index() {
    return view('nav/index', [
        'trendings' => Template::orderBy('views', 'DESC')->where('is_active', 'yes')->take(8)->get(),
        'latests_downloads' => Downloads::orderBy('id', 'DESC')->take(8)->get(),
    ]);
}

'latests_downloads' => Downloads::orderBy('id', 'DESC')->take(8)->get() function 只给了我:

ID 用户身份 product_id
1 7 10
2 9 2
3 45 86
4 88 85
5 5 2
6 7 7
7 5 5
8 9 6

参考方案1

  1. 将以下方法添加到您的Download model class (如果它们不存在。)
public function user()
{
    return $this->belongsTo(User::class, 'user_id');
}

public function product()
{
    return $this->belongsTo(Product::class, 'product_id');
}
  1. 更改您的 controller。
'latests_downloads' => Downloads::orderBy('id', 'DESC')->take(8)->get(),

// replace with the following

'latests_downloads' => Downloads::with(['user', 'product'])->orderBy('id', 'DESC')->take(8)->get(),
  1. 在您的视图文件中获取它。
@foreach($latest_downloads as $latest_download)

User Id: {{ $latest_download->user->id }}
Product Id: {{ $latest_download->product->id }}

@endforeach

[英文标题]select few from one table and based on value fetch from another table


声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。