質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Laravel 5

Laravel 5は、PHPフレームワークLaravelの最新バージョンで、2014年11月に発表予定です。ディレクトリ構造がが現行版より大幅に変更されるほか、メソッドインジェクションやFormRequestの利用が可能になります。

Q&A

解決済

2回答

7180閲覧

Laravelのリレーションでテーブルが取得できません

dauto

総合スコア38

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Laravel 5

Laravel 5は、PHPフレームワークLaravelの最新バージョンで、2014年11月に発表予定です。ディレクトリ構造がが現行版より大幅に変更されるほか、メソッドインジェクションやFormRequestの利用が可能になります。

0グッド

3クリップ

投稿2019/08/27 00:08

編集2019/08/27 10:20

開発環境

Laravel 5.8.26

困っている事

私は現在、LaravelでEC-CUBE4のSQLを使用し、以下の様なリレーションを作り、dtb_productテーブルと一対一のdtb_product_imageテーブルを取得しようとしています。
イメージ説明
dtb_customerテーブルからdtb_productテーブルへの多対多リレーションは実装できたのですが、dtb_product_imageテーブルを取得する事ができません。

試した事

belongsToManyメソッドにhasOneメソッドを組み合わせてコードを作成したのですが、下記のエラーが表示されました。

Customer.php

PHP

1<?php 2 3namespace App; 4 5use Laravel\Passport\HasApiTokens; 6use Illuminate\Notifications\Notifiable; 7use Illuminate\Foundation\Auth\User as Authenticatable; 8 9class Customer extends Authenticatable 10{ 11 use HasApiTokens, Notifiable; 12 13 /** 14 * The table associated with the model. 15 * 16 * @var string 17 */ 18 protected $table = 'dtb_customer'; 19 20 protected $with = ['ticket']; 21 22 public function ticket() 23 { 24 $ticket = $this->belongsToMany( 25 'App\Product', 26 'dtb_ticket', 27 'customer_id', 28 'ticket_id' 29 ); 30 $ticket_all = $ticket->hasone('App\Product_Image', 'product_id'); 31 return $ticket_all; 32 } 33 34 /** 35 * The attributes that are mass assignable. 36 * 37 * @var array 38 */ 39 protected $fillable = [ 40 'name', 'email', 'password', 41 ]; 42 43 /** 44 * The attributes that should be hidden for arrays. 45 * 46 * @var array 47 */ 48 protected $hidden = [ 49 'password', 'remember_token', 50 ]; 51 52 /** 53 * The attributes that should be cast to native types. 54 * 55 * @var array 56 */ 57 protected $casts = [ 58 'email_verified_at' => 'datetime', 59 ]; 60}

エラー

error

1Illuminate\Database\Eloquent\RelationNotFoundException: Call to undefined relationship [ticket] on model [App\Customer]. in file /var/www/html/siro/vendor/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php on line 34

dtb_product_imageテーブルのfile_nameカラムを取得するには何処を修正すればいいのでしょうか。

追記

エンティティに以下のコードを追加しましたが、取得する事はできませんでした。
お手数ですが問題点を教えて頂けないでしょうか。

Product.php

php

1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Model; 6 7class Product extends Model 8{ 9 protected $table = 'dtb_product'; 10 11 public function image() 12 { 13 return $this->hasone('App\Product_Image', 'product_id', 'id'); 14 } 15}

Product_Image.php

php

1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Model; 6 7class Product_Image extends Model 8{ 9 protected $table = 'dtb_product_image'; 10}

AuthController.php

php

1<?php 2 3namespace App\Http\Controllers\Auth; 4use App\User; 5use Carbon\Carbon; 6use Illuminate\Http\Request; 7use App\Http\Controllers\Controller; 8use Illuminate\Support\Facades\Auth; 9class AuthController extends Controller 10{ 11 public function login(Request $request) { 12 $request->validate([ 13 'email' => 'required|string|email', 14 'password' => 'required|string', 15 //'remember_me' => 'boolean' 16 ]); 17 $credentials = request(['email', 'password']); 18 if(!Auth::attempt($credentials)) 19 return response()->json([ 20 'message' => 'Unauthorized' 21 ], 401); 22 $user = $request->user(); 23 $tokenResult = $user->createToken('Personal Access Token'); 24 $token = $tokenResult->token; 25 if ($request->remember_me) 26 $token->expires_at = Carbon::now()->addWeeks(1); 27 $token->save(); 28 return response()->json([ 29 'access_token' => $tokenResult->accessToken, 30 'token_type' => 'Bearer', 31 'expires_at' => Carbon::parse( 32 $tokenResult->token->expires_at 33 )->toDateTimeString() 34 ]); 35 } 36 37 public function logout(Request $request) 38 { 39 $request->user()->token()->revoke(); 40 return response()->json([ 41 'message' => 'Successfully logged out' 42 ]); 43 } 44 45 /** 46 * Get the authenticated User 47 * 48 * @return [json] user object 49 */ 50 public function user(Request $request) 51 { 52 return response()->json($request->user()); 53 } 54}

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

ベストアンサー

php

1$ticket_all = $ticket->hasone('App\Product_Image', 'product_id');

このような当てずっぽうでは動作しません。

まずProductからProductImageに対してhasOneなりhasManyを定義します。

そして

①CustomerからProductを取得
②ProductからProductImageを取得

という順で取得します。

投稿2019/08/27 00:15

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

dauto

2019/08/27 04:17

Productエンティティに質問に追記したコードをに記入したのですが、dtb_product_imageテーブルを取得することができませんでした。 問題点があれば教えて頂けると幸いです’。
退会済みユーザー

退会済みユーザー

2019/08/27 04:29

> 取得することができません というのはどういうことかを詳細に記述して下さい。
dauto

2019/08/27 05:18

エラーは表示されないのですが、JSONとしてCustomerのデータを出力した時にProductImageのデータのみ出力できませんでした。
退会済みユーザー

退会済みユーザー

2019/08/27 05:28

どういうコードを書いてそうなったのかを記述して下さい。
退会済みユーザー

退会済みユーザー

2019/08/27 05:29

現状コントローラの記述がないと思います。
dauto

2019/08/27 10:21

Controllerのコードを追記させて頂きました。
dauto

2019/08/27 20:08

追記したProductエンティティに protected $with = 'image'; とEagerローディングを追加しキャッシュを削除することによって解決しました。 回答して下さった方ありがとうございました。
guest

0

Laravelの命名規則に則ってやるとこうなるはず。

イメージ説明

Migration

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCustomersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('customers', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('customers'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProductImagesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('product_images', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('product_id'); $table->timestamps(); $table->foreign('product_id')->references('id')->on('products'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('product_images'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCustomerProductTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('customer_product', function (Blueprint $table) { $table->unsignedBigInteger('customer_id'); $table->unsignedBigInteger('product_id'); $table->unique(['customer_id', 'product_id']); $table->foreign('customer_id')->references('id')->on('customers'); $table->foreign('product_id')->references('id')->on('products'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('customer_product'); } }

Model

<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class Customer extends Model { public function products(): BelongsToMany { return $this->belongsToMany(Product::class); } }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasOne; class Product extends Model { public function customers(): BelongsToMany { return $this->belongsToMany(Customer::class); } public function product_image(): HasOne { return $this->hasOne(ProductImage::class)->withDefault(); } }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class ProductImage extends Model { public function product(): BelongsTo { return $this->belongsTo(Product::class); } }

このように定義すれば、コントローラーから

$customers = Customer::with('products.product_images')->get(); dd($customers);

こうすれば取れるはず。

投稿2019/08/27 10:53

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問