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

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

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

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

Laravel

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

PHP

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

データベース

データベースとは、データの集合体を指します。また、そのデータの集合体の共用を可能にするシステムの意味を含めます

データ構造

データ構造とは、データの集まりをコンピュータの中で効果的に扱うために、一定の形式に系統立てて格納する形式を指します。(配列/連想配列/木構造など)

Q&A

解決済

1回答

1784閲覧

Laravel リレーション定義したデータを抽出する際に関して

退会済みユーザー

退会済みユーザー

総合スコア0

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

Laravel

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

PHP

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

データベース

データベースとは、データの集合体を指します。また、そのデータの集合体の共用を可能にするシステムの意味を含めます

データ構造

データ構造とは、データの集まりをコンピュータの中で効果的に扱うために、一定の形式に系統立てて格納する形式を指します。(配列/連想配列/木構造など)

0グッド

0クリップ

投稿2020/09/19 15:21

前提・実現したいこと

Laravelで図書館で借りた本をユーザが確認できる様なものを作成しています。
リレーション定義したものを取得することは以前の質問で解決することができたのですが、複数のレコードがあった際にそれを取得することができましたので問題はないのかと思っています。
しかし、当日分のデータをその借りた時間から取得するというコードがうまく動作しなくなってしまいました。当日分のデータは book_userテーブルのcreatedを指しています。

該当のソースコード

PHP

1$user = User::with(['books'])->latest(); 2foreach ($user->books as $book) { 3 dump($book->pivot->created_at); 4 dump($book->book_name); 5}

試したこと

下記の様にwhereで繋げてみました。
結果はエラーが表示されなかったのですが、当日のデータ以外も表示されてしまいました。

PHP

1$user = User::with(['books' => function($q) { 2 $q->where('book_user.created_at', '>', date('Y-m-d')); 3}])->latest(); 4foreach ($user->books as $book) { 5 dump($book->pivot->created_at); 6 dump($book->book_name); 7}

補足情報(FW/ツールのバージョンなど)

Laravel 7.28.1
PHP 7.X
MySQL

create_users_table.php

PHP

1 $table->id(); 2 $table->string('name'); 3 $table->string('email')->unique(); 4 $table->timestamp('email_verified_at')->nullable(); 5 $table->string('password'); 6 $table->rememberToken(); 7 $table->timestamps();

create_book_user_table.php

PHP

1 $table->id(); 2 $table->unsignedBigInteger('user_id'); 3 $table->unsignedBigInteger('book_id'); 4 $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 5 $table->foreign('book_id')->references('id')->on('books')->onDelete('cascade'); 6 $table->timestamps();

create_book_table.php

$table->id(); $table->char('book_name'); $table->bigInteger('book_price'); $table->text('book_detail'); $table->timestamps();

App\User.php

PHP

1<?php 2 3namespace App; 4 5use Illuminate\Contracts\Auth\MustVerifyEmail; 6use Illuminate\Foundation\Auth\User as Authenticatable; 7use Illuminate\Notifications\Notifiable; 8 9class User extends Authenticatable 10{ 11 use Notifiable; 12 13 /** 14 * The attributes that are mass assignable. 15 * 16 * @var array 17 */ 18 protected $fillable = [ 19 'name', 'email', 'password', 20 ]; 21 22 /** 23 * The attributes that should be hidden for arrays. 24 * 25 * @var array 26 */ 27 protected $hidden = [ 28 'password', 'remember_token', 29 ]; 30 31 /** 32 * The attributes that should be cast to native types. 33 * 34 * @var array 35 */ 36 protected $casts = [ 37 'email_verified_at' => 'datetime', 38 ]; 39 40 public function books(){ 41 return $this->belongsToMany("App\Book")->withTimestamps(); 42 } 43 44}

App\Book.php

PHP

1 <?php 2 3 namespace App; 4 5 use Illuminate\Database\Eloquent\Model; 6 7 class Book extends Model 8 { 9 protected $table = "books"; 10 11 protected $fillable = [ 12 'book_name', 'book_price', 'book_detail', 13 ]; 14 15 public function users(){ 16 return $this->belongsToMany("App\User"); 17 } 18 }

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

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

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

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

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

hentaiman

2020/09/19 15:42

勉強の為ならともかく、リレーション張ったからと言って無理に使う必要無いですよ
yuki84web

2020/09/20 02:45

whereの条件に'>'とありますが、これの意味は理解されてますか?
guest

回答1

0

ベストアンサー

Migrations

php

1<?php 2 3use Illuminate\Database\Migrations\Migration; 4use Illuminate\Database\Schema\Blueprint; 5use Illuminate\Support\Facades\Schema; 6 7class CreateBooksTable extends Migration 8{ 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::create('books', function (Blueprint $table) { 17 $table->id(); 18 $table->string('name'); 19 $table->bigInteger('price'); 20 $table->string('detail', 1000)->nullable(); 21 $table->timestamps(); 22 }); 23 } 24 25 /** 26 * Reverse the migrations. 27 * 28 * @return void 29 */ 30 public function down() 31 { 32 Schema::dropIfExists('book'); 33 } 34} 35

php

1<?php 2 3use Illuminate\Database\Migrations\Migration; 4use Illuminate\Database\Schema\Blueprint; 5use Illuminate\Support\Facades\Schema; 6 7class CreateBookUserTable extends Migration 8{ 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::create('book_user', function (Blueprint $table) { 17 $table->id(); 18 $table->unsignedBigInteger('user_id'); 19 $table->unsignedBigInteger('book_id'); 20 $table->timestamps(); 21 22 $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 23 $table->foreign('book_id')->references('id')->on('books')->onDelete('cascade'); 24 }); 25 } 26 27 /** 28 * Reverse the migrations. 29 * 30 * @return void 31 */ 32 public function down() 33 { 34 Schema::dropIfExists('book_user'); 35 } 36}

Models

php

1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Relations\BelongsToMany; 6use Illuminate\Foundation\Auth\User as Authenticatable; 7use Illuminate\Notifications\Notifiable; 8 9class User extends Authenticatable 10{ 11 use Notifiable; 12 13 /** 14 * The attributes that are mass assignable. 15 * 16 * @var array 17 */ 18 protected $fillable = [ 19 'name', 'email', 'password', 20 ]; 21 22 /** 23 * The attributes that should be hidden for arrays. 24 * 25 * @var array 26 */ 27 protected $hidden = [ 28 'password', 'remember_token', 29 ]; 30 31 /** 32 * The attributes that should be cast to native types. 33 * 34 * @var array 35 */ 36 protected $casts = [ 37 'email_verified_at' => 'datetime', 38 ]; 39 40 /** 41 * @return BelongsToMany 42 */ 43 public function books(): BelongsToMany 44 { 45 return $this->belongsToMany(Book::class) 46 ->withTimestamps(); 47 } 48} 49

php

1<?php 2 3namespace App; 4 5use Carbon\Traits\Timestamp; 6use Illuminate\Database\Eloquent\Model; 7use Illuminate\Database\Eloquent\Relations\BelongsToMany; 8 9class Book extends Model 10{ 11 use Timestamp; 12 13 protected $fillable = [ 14 'name', 15 'price', 16 'detail', 17 ]; 18 19 /** 20 * @return BelongsToMany 21 */ 22 public function users(): BelongsToMany 23 { 24 return $this->belongsToMany(User::class) 25 ->withTimestamps(); 26 } 27} 28

factories

php

1<?php 2 3/** @var \Illuminate\Database\Eloquent\Factory $factory */ 4 5use App\User; 6use Faker\Generator as Faker; 7use Illuminate\Support\Str; 8 9/* 10|-------------------------------------------------------------------------- 11| Model Factories 12|-------------------------------------------------------------------------- 13| 14| This directory should contain each of the model factory definitions for 15| your application. Factories provide a convenient way to generate new 16| model instances for testing / seeding your application's database. 17| 18*/ 19 20$factory->define(User::class, function (Faker $faker) { 21 return [ 22 'name' => $faker->name, 23 'email' => $faker->unique()->safeEmail, 24 'email_verified_at' => now(), 25 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 26 'remember_token' => Str::random(10), 27 'created_at' => $faker->dateTime('-10 years'), 28 'updated_at' => $faker->dateTime('-10 years'), 29 ]; 30});

php

1<?php 2 3/** @var \Illuminate\Database\Eloquent\Factory $factory */ 4 5use App\Book; 6use Faker\Generator as Faker; 7 8$factory->define(Book::class, function (Faker $faker) { 9 return [ 10 'name' => $faker->word, 11 'price' => $faker->numberBetween(1000, 3000), 12 'detail'=>null, 13 'created_at' => $faker->dateTime('-10 years'), 14 'updated_at' => $faker->dateTime('-10 years'), 15 ]; 16}); 17

Seeder

php

1<?php 2 3use Illuminate\Database\Seeder; 4 5class UserSeeder extends Seeder 6{ 7 /** 8 * Run the database seeds. 9 * 10 * @return void 11 */ 12 public function run() 13 { 14 factory(\App\User::class, 5)->create(); 15 } 16}

php

1<?php 2 3use Illuminate\Database\Seeder; 4 5class BookSeeder extends Seeder 6{ 7 /** 8 * Run the database seeds. 9 * 10 * @return void 11 */ 12 public function run() 13 { 14 factory(\App\Book::class, 100)->create()->each(function (\App\Book $book) { 15 $count = rand(0, \App\User::all()->count()); 16 $user_ids = \App\User::query()->inRandomOrder()->take($count)->pluck('id'); 17 18 for ($i = 0; $i < $count; $i++) { 19 $start = now()->subYears(rand(0, 10))->subDays(rand(0, 365)); 20 $book->users()->attach($user_ids[$i], [ 21 'created_at' => $start 22 ]); 23 } 24 }); 25 } 26}

UserController

php

1<?php 2 3namespace App\Http\Controllers; 4 5use App\User; 6use Illuminate\View\View; 7 8class UserController extends Controller 9{ 10 /** 11 * Display a listing of the resource. 12 * 13 * @return View 14 */ 15 public function index(): View 16 { 17 $users = User::with(['books' => function ($query) { 18 $query->whereDate('pivot_created_at', now()); 19 }])->get(); 20 return view('users.index', compact('users')); 21 } 22}

Blade

views/users/index.blade.php

php

1<!doctype html> 2<html lang="ja"> 3<head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" 6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9</head> 10<body> 11<div> 12 <table> 13 <thead> 14 <tr> 15 <th>ユーザーID</th> 16 <th>ユーザー名</th> 17 <th>メールアドレス</th> 18 <th>本日貸出した本</th> 19 <th>貸出日時</th> 20 </tr> 21 </thead> 22 <tbody> 23 @foreach ($users as $user) 24 <tr> 25 <td>{{ $user->id }}</td> 26 <td>{{ $user->name }}</td> 27 <td>{{ $user->email }}</td> 28 <td>{{ $user->books->first()->name }}</td> 29 <td>{{ $user->books->first()->pivot->created_at }}</td> 30 </tr> 31 @endforeach 32 </tbody> 33 </table> 34</div> 35</body> 36</html>

投稿2020/09/20 04:40

編集2020/09/20 05:30
phper.k

総合スコア3923

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

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

phper.k

2020/09/20 05:30

細かな調整はご自身でやってください。
退会済みユーザー

退会済みユーザー

2020/09/20 12:07

ご丁寧にありがとうございます! 一点気になったのですが、Modelのリレーション定義において以下の様に ::classとあったのですが、*2でも意味は変わらず明示的に記述されているのでしょうか? return $this->belongsToMany(User::class) *2 return $this->belongsToMany("App\User");
phper.k

2020/09/20 13:46 編集

「明示的に記述されているのでしょうか?」←どういう意味で聞いているんですか? 質問の意味がわかりません。
退会済みユーザー

退会済みユーザー

2020/09/21 05:48 編集

return $this->belongsToMany(User::class); return $this->belongsToMany("App\User"); 前者と後者の違いがわからない為質問させていただきました。
phper.k

2020/09/21 05:50

機能としては同じです。 dd(User::class); として実行してみれば、どんな値になっているかわかるはず。
退会済みユーザー

退会済みユーザー

2020/09/21 06:11

ありがとうございます!確認したところ変わりない様でした。
退会済みユーザー

退会済みユーザー

2020/09/21 06:12

度々すいませんが、複数ある時も1つのデータしか取得できない様なのですがご確認いただけると幸いです
退会済みユーザー

退会済みユーザー

2020/09/21 06:17

usersをdumpしたところ一つの配列しかありませんでした。
phper.k

2020/09/21 06:20

それ、私がすること? 仕事じゃあるまいし、まして私に割り当てられたタスクじゃないんですよ
phper.k

2020/09/21 06:24 編集

> 複数ある時も1つのデータしか取得できない様なのです > usersをdumpしたところ一つの配列しかありませんでした。 聞く前にそれが、回答者に問うて、適切かどうか判断しているんでしょうか? > 複数ある時も1つのデータしか取得できない様なのです 「何が」複数あるのか? > usersをdumpしたところ一つの配列しかありませんでした。 データが一つしかなけりゃ当然じゃない?ちゃんとデータはあるの? 前提条件を共有せずに聞くことかい?
退会済みユーザー

退会済みユーザー

2020/09/21 06:34

すいません。以前の質問よりご指摘いただいた貸し出し履歴、複数回あるときに正しく取得できるかどうかの話をしていました。質問本文にある以前のコードでは貸し出し履歴、複数回ある時は取得できていたのですが、回答していただいたコードでは貸し出し履歴、複数回ある時取得できていなかった為質問させていただいた次第です。 > 貸し出し履歴、複数回あるときに正しい貸し出し日時を取得できるかどうか確認してみてください。
phper.k

2020/09/21 06:36

<td>{{ $user->books->first()->name }}</td> <td>{{ $user->books->first()->pivot->created_at }}</td> ここを適切に編集すれば良いということは気づけないですか?
退会済みユーザー

退会済みユーザー

2020/09/21 06:39

ありがとうございます。こちら本題の件は解決しましたのでベストアンサーにさせていただきます。
退会済みユーザー

退会済みユーザー

2020/09/21 06:58

> ここを適切に編集すれば良いということは気づけないですか? 現状見当がつかないです、、
phper.k

2020/09/21 07:43

> 現状見当がつかないです、、 とりあえずコピペでやってる感じなんですかね・・・
退会済みユーザー

退会済みユーザー

2020/09/21 08:34

first() とすることでfirstメソッドは指定された真偽テストをパスしたコレクションの最初だけの要素を取得していることが原因かと思い、全ての要素を取得するコレクションとしてget()やall()など試しているのですがエラーとなってしまっている現状なのです、、 参考にしたドキュメント https://readouble.com/laravel/7.x/ja/collections.html#method-first
phper.k

2020/09/21 08:39

ロシアンルーレットみたいなコードの書き方してるな・・ dd($user->books) でまず、$user->books がどのクラスなのか確認しなよ。 クラスがわかれば、そのクラスが持つメソッドが当たりつくじゃん。
退会済みユーザー

退会済みユーザー

2020/09/21 12:36

@foreach ($users as $user) @foreach ($user->books as $book) {{ $book->name }} @endforeach @endforeach とすることで取得できました。
退会済みユーザー

退会済みユーザー

2020/09/21 12:45

大変失礼しました。先程のものではできず以下でできた様です。。 @php foreach ($users as $user) i = 0; $user->books[i]['book_name'] i++; endforeach @endphp
退会済みユーザー

退会済みユーザー

2020/09/21 12:53

あまり良くない記述ということでしょうか?
phper.k

2020/09/21 13:04

それ以前に、それは動かないでしょ。 ループの中で $i イテレータを回すのもナンセンスです。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問