如何仅从雄辩的查询中获取关系

Ale*_*pov 6 laravel eloquent

我得到以下代码:

$popularProducts = PopularProduct::with('product')->get();

这就是我从popular_products(仅包含product_id)表中获取所有产品的方式,其中包含表的关系products。但我有这个结果:

Collection {#409 ?
  #items: array:1 [?
    0 => PopularProduct {#411 ?
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:4 [?]
      #original: array:4 [?]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [?
        "product" => Product {#462 ?}
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [?]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我只需要拿relations->product场。我怎么能接受呢?

小智 6

您可以使用whereHas方法(如果这些表之间存在关系)

$popular_products = Product::whereHas('products', function ($query) {
      $query->where('popular_products',$ids);
 })->get()
Run Code Online (Sandbox Code Playgroud)


ait*_*lla 6

你可以这样做

$products = PopularProduct::with('product')->get()->pluck('product');
Run Code Online (Sandbox Code Playgroud)

如果你喜欢结果被键入,你可以这样做

$products = PopularProduct::with('product')->get()->pluck('product','id');
Run Code Online (Sandbox Code Playgroud)

// you can key it with **id** of the table (popularProduct) or by **id_product** of relationship (product)

如果您只想从关系中检索特定字段,您可以尝试这样的操作

 $products = PopularProduct::with('product:id,product_name')->get()->pluck('product','id');
Run Code Online (Sandbox Code Playgroud)


Ale*_*nin 0

您需要迭代集合:

@foreach ($popularProducts as $popularProduct)
    {{ $popularproduct->product->id }}
@endforeach
Run Code Online (Sandbox Code Playgroud)

如果您只想获取集合中的所有产品,请使用以下pluck()方法:

$products = $popularProducts->pluck('product');
Run Code Online (Sandbox Code Playgroud)

更新

在评论中,您说过您想links直接从数据库获取:

Product::has('popularProduct')->pluck('links');
Run Code Online (Sandbox Code Playgroud)

popularProduct如果您已在模型中定义了关系,则这将起作用Product