简体   繁体   English

在 Laravel 中,我的表列被连接覆盖,我该如何解决?

[英]In Laravel my table columns overwrite with join, how can i solve?


I have a mini problem in my application...我的应用程序中有一个小问题...
I want to get all products from the products table along with the category name from the categories table and get stock of each product from products_attribute table...我想从产品表中获取所有产品以及从类别表中获取类别名称,并从 products_attribute 表中获取每个产品的库存...
the problem is product table id overwrite with products_attribute id.问题是产品表 id 覆盖了 products_attribute id。 In the product_attributes table, only 116 rows but products table has 177 rows and the loop gets only 116 rows with products_attribute id.在 product_attributes 表中,只有 116 行,而 products 表有 177 行,循环只得到 116 行,带有 products_attribute id。

Product Table (Screenshot) Product Table (截图)

Product Attributes Table (Screenshot) Product Attributes Table (截图)

Categories Table (Screenshot) Categories Table (截图)

public function viewProducts(Request $request)
{
    $products = Product::join('categories', 'categories.id', 'products.category_id')->join('products_attributes', 'products_attributes.product_id', 'products.id')->get();
    $products = json_decode(json_encode($products));

    return view('admin.products.view_products')->with(compact('products'));
}

Laravels join function default is inner join so You will need to use the leftJoin method. Laravels join 函数默认是内连接,所以你需要使用leftJoin方法。 (See \\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder@join ) (见\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder@join

我希望它会有所帮助.. 如何使用left join

$products = Product::join('categories', 'categories.id', 'products.category_id')->leftjoin('products_attributes', 'products_attributes.product_id', 'products.id')->get();

You have to use aliases to preserve columns from the base table that will be overwritten by your joining table(s):您必须使用别名来保留基表中的列,这些列将被您的连接表覆盖:

$products = Product::select('*', \DB::raw("product.id as product_id"))->join('categories', 'categories.id', '=', 'product.id')->get();

You can then access the product id using: $product->product_id然后,您可以使用以下方法访问产品 ID: $product->product_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM