如何在 product table 中显示用户名? API laravel 8 使用 eloquent

How to display user name inside product table ? API laravel 8 use eloquent

我有 2 个 table:

Table User:

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 网络..

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

我得到的输出是:

我应该在控制器中更改什么?提前致谢... :) 我是 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();

注意文档中的注释

When using this feature, you should always include the id column and any relevant foreign key columns in the list of columns you wish to retrieve.

添加产品型号

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'
            ]);
        }
    }
}