【问题标题】:How to display user name inside product table ? API laravel 8 use eloquent如何在产品表中显示用户名? API laravel 8 使用 eloquent
【发布时间】:2021-01-08 15:53:55
【问题描述】:

我有 2 张桌子:

User:

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

我得到的输出是:

我应该在控制器中进行哪些更改?在此先感谢... :) 我是 laravel 的新手

【问题讨论】:

  • 一个选项:使用连接而不是关系构建查询。
  • 请以文字而非图片的形式提供您的代码。这将使在谷歌或其他方面更容易找到它。请参阅How to Ask 了解更多信息。

标签: php laravel eloquent laravel-8 rest


【解决方案1】:

加入方法:

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

【讨论】:

    【解决方案2】:

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

    $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 列和任何相关的外键列。

    【讨论】:

      【解决方案3】:

      添加产品型号

      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
      

      【讨论】:

        猜你喜欢
        • 2020-10-26
        • 2020-08-16
        • 1970-01-01
        • 2019-06-18
        • 1970-01-01
        • 2013-12-07
        • 2018-01-22
        • 2018-12-05
        • 1970-01-01
        相关资源
        最近更新 更多