完整性约束违反联接表MySql

时间:2019-07-10 04:36:40

标签: php mysql laravel laravel-5

我有三个推荐表,products和products_photos。在recommended表和products_photos表中,它们都具有product_id列。我想将他们(三个)加入一起,但遇到这个错误Integrity constraint violation: 1052 Column 'product_id' in field list,我该如何加入他们?

Route::get('/info', function(){
$products = DB::table('recommends')
->leftJoin('products','recommends.product_id','products.id')
->join('products_photos','products_photos.product_id','products.id' 
)
->select('product_id','name','price', DB::raw('count(*) as total'))
->groupBy('product_id','name','price')
->get();
//dd($products);

});

2 个答案:

答案 0 :(得分:2)

您从未指定在联接调用中使用的等于/不等于运算符。尝试这样做,并使用适当的别名限定您选择的所有列:

.
.
environment:
  sdk: ">=2.2.2 <3.0.0"

我假设Route::get('/info', function() { $products = DB::table('recommends AS r') ->leftJoin('products AS p', 'r.product_id', '=', 'p.id') ->join('products_photos AS pp', 'pp.product_id', '=', 'p.id') ->select('p.id', 'p.name', 'p.price', DB::raw('COUNT(*) AS total')) ->groupBy('p.id', 'p.name', 'p.price') ->get(); }); 具有productsidname列。

答案 1 :(得分:0)

问题出在您的Select语句中。您正在选择product_id,在推荐和产品中都可以找到... ->select('recommends.product_id','name','price', DB::raw('count(*) as total')) ... ,选择此类列时,您必须提供要从中获取该列的表名,例如:

# Characters for building string.

curly_bracket_left  <- "{"
curly_bracket_right <- "}"
colon               <- ": "
comma               <- ", "

escaped_quotation   <- "\""

# Key-value-pairs data.

key_title_1         <- "epic"
value_title_1       <- "sweden"

key_title_2         <- "currency"
value_title_2       <- "SEK"

# Build string.

string <- paste0(
    curly_bracket_left,

        escaped_quotation,
        key_title_1,
        escaped_quotation,
    colon,

        escaped_quotation,
        value_title_1,
        escaped_quotation,
    comma,

        escaped_quotation,
        key_title_2,
        escaped_quotation,
    colon,

        escaped_quotation,
        value_title_2,
        escaped_quotation

    curly_bracket_right
)

print(string)