如何在产品表中显示用户名? API laravel 8 使用 eloquent

问题描述

我有 2 张桌子:

User

table user

Product

table product

我有模型关系:

User 模型:

public function product() { 
    return $this->hasMany(Product::class); 
}

Product 模型:

protected $fillable = [
    'user_id','nama','harga','deskripsi','kategori_id','gambar',];

public function user()
{
    return $this->belongsTo(User::class);
}

这是我的控制器:

class GetProductController extends Controller
{
    public function index() {
        $product = Product::with(['user'])->get();

        if($product) {
            return response()->json([
                'success' => 1,'message' => 'success get  data','products' => collect($product)
            ]);
        } else {
            return response()->json([
                'success' => 0,'message' => 'Failed get data'
            ]);
        }
    }
}

这是我的路线 Api :

Route::get('getproduct',[GetProductController::class,'index']);

我想将 API 用于移动应用......而不是 Api web..

问题是:如何在表产品中的表用户中仅显示name

我得到的输出是:

the problem

我应该在控制器中更改什么?提前致谢... :) 我是 Laravel 的新手

解决方法

过去,您可以将 select 闭包传递到查询中以获取所需的列:

$product = Product::with(['user' => function($query) { 
                $query->select('id','name');
           ])
           ->get();

但是,使用 Laravel 8,您现在可以eager load the columns quicker

$product = Product::with(['user:id,name'])->get();

注意文档中的注释

使用此功能时,您应始终在要检索的列列表中包含 id 列和任何相关的外键列。

,

添加产品型号

public function getUser()
{
    return $this->hasOne('App\Models\User','id','user_id');
}

控制器

 $product = Product::with(['getUser'])->get();

查看

@foreach ($product as $item)
    {{ $item->getUser->name }}
@endforeach
,

加入方式:

class GetProductController extends Controller
{
public function index(){
    $product = Product::join('users','users.id','products.user_id')
                        ->select('users.name as user_name','products.*')->get();

        if($product){
            return response()->json([
                'success' => 1,'message' => 'success get  data','products' => collect($product) //get() method returns a collection,no need to collect again
            ]);
        } else {
            return response()->json([
                'success' => 0,'message' => 'failed get data'
            ]);
        }
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...