laravelを勉強し始めた初心者です
list.blade.phpに表示している一覧から「詳細表示」をクリックしたらクリックしたものの詳細画面がdetail.blade.phpで表示できるようにしたいと思っています
joinを使ってproductsテーブルとcompaniesテーブルを結合させ
findでproductsテーブル内の指定したidに関する情報だけを取得したいのですがidの指定がうまくできていないとエラーが出てしまいます
自分ではどうにもできなかったので投稿しました
どなたかご助力頂けないでしょうか
productsテーブル 一部
+--------+------------+--------------+-------+-------+ | id | company_id | product_name | price | stock | +--------+------------+--------------+-------+-------+ | 1 | 1 | 商品1 | 100 | 10 | | 2 | 1 | 商品2 | 150 | 10 | | 3 | 2 | 商品3 | 200 | 20 | | 4 | 3 | 商品4 | 400 | 20 | +--------+------------+--------------+-------+-------+
companiesテーブル 一部
+--------+--------------+---------------------+ | id | company_name | representative_name | +--------+--------------+---------------------+ | 1 | 株式会社1 | 商品1 | | 2 | 株式会社2 | 商品2 | | 3 | 3株式会社 | 商品3 | +--------+--------------+---------------------+
list.blade.php 一部
<div class="links"> <table> <thead> <tr> <th>id</th> <th>メーカー名</th> <th>商品名</th> <th>価格</th> <th>在庫数</th> <th>商品画像</th> </tr> </thead> <tbody> @foreach ($products as $product) <tr> <td>{{ $product->id }}</td> <td>{{ $product->company_name }}</td> <td>{{ $product->product_name }}</td> <td>{{ $product->price }}</td> <td>{{ $product->stock }}</td> <td>{{ $product->img_path }}</td> <td><a href="{{ route('detail', ['id'=>$product->id]) }}" class="btn">詳細表示</a></td> </tr> @endforeach </tbody> </table> </div>
detail.blade.php 一部
<table> <thead> <tr> <th>商品情報ID</th> <th>メーカー</th> <th>商品名</th> <th>価格</th> <th>在庫数</th> </tr> </thead> <tbody> <tr> <td>{{ $details->id }}</td> <td>{{ $details->company_id }}</td> <td>{{ $details->product_name }}</td> <td>{{ $details->price }}</td> <td>{{ $details->stock }}</td> </tr> </tbody> </table>
web.php
Route::get('/detail/{id}','ProductController@showDetail')->name('detail');
ProductController 一部
class ProductController extends Controller { public function showDetail($id) { $model = new Product(); $details = $model->findId($id); return view('detail', compact('details')); } }
ProductModel 一部
class Product extends Model { public function findId($id) { $products = DB::table('products') ->select('products.id','company_name','product_name','price','stock') ->join('companies', 'products.company_id', '=', 'companies.id') ->find($id); return $products; } }
発生しているエラーメッセージ
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select `products`.`id`, `company_name`, `product_name`, `price`, `stock` from `products` inner join `companies` on `products`.`company_id` = `companies`.`id` where `id` = 1 limit 1)
試したこと
Model内のselectで'companies.id as companies_id'のように名前を変更することでエラーを回避できるというような記事をいくつか見たので試しましたが解決できませんでした
補足情報(FW/ツールのバージョンなど)
Laravel version
6.20.44
PHP version
7.4.16

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。