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

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

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

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

Q&A

解決済

2回答

1304閲覧

Laravelで作った図書館の貸し出しテーブルと本テーブルのリレーションの設定をしてビューファイルで表示をしたい

n18marron

総合スコア3

Laravel

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

0グッド

0クリップ

投稿2021/07/21 08:57

編集2021/07/21 09:54

前提・実現したいこと

表題の通りです。
ビューで貸し出しテーブルにリレーションしたusersテーブルのnameとbooksテーブルのtitleを表示させたいです。そのうえで貸し出しテーブルのreturn_dateがnullの値を抽出したいです。
ですがリレーション先へのアクセスができなくて詰まっています。

発生している問題・エラーメッセージ

Trying to get property 'title' of non-object

dd(&datas)をしてみたところ

Illuminate\Database\Eloquent\Collection {#310 ▼ #items: array:1 [▼ 0 => App\Models\Lending {#312 ▼ #table: "lendings" #fillable: array:5 [▼ 0 => "user_id" 1 => "book_id" 2 => "lent_date" 3 => "return_date" 4 => "status" ] +timestamps: false #connection: "sqlite" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] +preventsLazyLoading: false #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:6 [▼ "id" => "2" "user_id" => "2" "book_id" => "3" "lent_date" => "2021-6-30" "return_date" => null "status" => "0" ] #original: array:6 [▼ "id" => "2" "user_id" => "2" "book_id" => "3" "lent_date" => "2021-6-30" "return_date" => null "status" => "0" ] #changes: [] #casts: [] #classCastCache: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: [] #touches: [] #hidden: [] #visible: [] #guarded: array:1 [▼ 0 => "*" ] } ] }

該当のソースコード

###マイグレーションファイル

//database/migration/create_users_table <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
// database/migration/create_books_table <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBooksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('books', function (Blueprint $table) { $table->increments('id'); $table->string('title'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('books'); } }
// database/migration/create_lendings_table <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateLendingsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('lendings', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->integer('book_id'); $table->timestamp('lent_date'); $table->timestamp('return_date')->nullable(); $table->boolean('status'); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); $table->foreign('book_id') ->references('id') ->on('books') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('lendings'); } }

モデル

// App/Model/Book <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\Lending; class Book extends Model { protected $table = 'books'; protected $fillable = ['title']; public $timestamps = false; public function lendings() { return $this->hasMany(Lending::class, 'book_id'); } public function getData() { $datas = [ 'id' => $this->id, 'title' => $this->title, ]; return $datas; } }
// App/Models/User <?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use App\Models\Lending; class User extends Authenticatable { use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public $timestamps = false; public function lendings() { return $this->hasMany(Lending::class); } }
// App/Models/Lending <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\User; use App\Models\Book; class Lending extends Model { protected $table = 'lendings'; protected $fillable = [ "user_id", 'book_id', 'lent_date', 'return_date', 'status', ]; public $timestamps = false; public function user() { return $this->belongsTo(User::class, 'id'); } public function book() { return $this->belongsTo(Book::class, 'id'); } public function getData() { $datas = [ 'id' => $this->id, 'user_id' => $this->user_id, 'book_id' => $this->book_id, 'lent_date' => $this->lent_date, 'return_date' => $this->status, ]; return $datas; } }

シーダー

// database/seeder/UserSeeder <?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; class UserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i = 1; $i <= 10; $i++) { DB::table('users')->insert([ 'id' => $i, 'name' => 'user' . $i, 'email' => 'email' . $i . '@gmail.com', 'password' => Hash::make('password'), ]); } } }
//database/seeder/BookSeeder <?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class BookSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i = 1; $i <= 10; $i++) { DB::table('books')->insert([ 'title' => 'title' . $i, ]); } } }
// database/seeder/LendingSeeder <?php namespace Database\Seeders; use Illuminate\Support\Facades\DB; use Illuminate\Database\Seeder; class LendingSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('lendings')->insert([ 'user_id' => '1', 'book_id' => '2', 'lent_date' => '2021-6-30', 'return_date' => '2021-7-4', 'status' => '0', ]); DB::table('lendings')->insert([ 'user_id' => '2', 'book_id' => '3', 'lent_date' => '2021-6-30', 'return_date' => null, 'status' => '0', ]); } }

コントローラ

// App/Http/Controller/LendingController <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Lending; use App\Models\Book; class LendingController extends Controller { // 貸出中の本を表示 public function index() { $datas = Lending::whereNull('return_date')->get(); return view('index', ['datas' => $datas]); } }

ビュー

@extends('layouts.app') @section('content') @foreach($datas as $data) id{{ $data->id }} 本の名前{{ $data->books->title }} 借りての名前{{ $data->users->name }} 貸し出し日{{ $data->lent_date }} <br> @endforeach @endsection

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

Laravel 8.49.2

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

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

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

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

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

guest

回答2

0

mikkameさんのコメントをまとめてcloseします。

// LendingController class LendingController extends Controller { // 貸出中の本を表示 public function index() { $datas = Lending::whereNull('return_date') ->with('book') ->with('user') ->get(); return view('index', ['datas' => $datas]); } }
// index.blade.php @extends('layouts.app') @section('content') @foreach($datas as $data) id{{ $data->id }} title{{ $data->book->title }} name{{ $data->user->name }} lent_date{{ $data->lent_date }} <br> @endforeach @endsection

投稿2021/07/21 10:21

n18marron

総合スコア3

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

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

0

ベストアンサー

Lending::where('return_date', null)->get();

ではなく
Lending::whereNull('return_date')->get();
ですね

投稿2021/07/21 09:20

mikkame

総合スコア5036

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

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

n18marron

2021/07/21 09:48

whereNullに変更してddしてみたところ、relationのところが[]だけなんですが、この状態ってリレーションはちゃんと設定されているでしょうか
mikkame

2021/07/21 09:54

そのプロパティにアクセスした時にロードされる(気がする)と思います。 ->with('books')->get()にしたら最初から入る気がします
n18marron

2021/07/21 10:01

Illuminate\Database\Eloquent\RelationNotFoundException Call to undefined relationship [books] on model [App\Models\Lending]. でした。
mikkame

2021/07/21 10:13

booksではなくbookですね・・・
n18marron

2021/07/21 10:17

ありがとうございます!モデルを指定するんですね。勉強になりました。
mikkame

2021/07/21 10:18

モデルではなく定義した名前ですね
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問