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

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

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

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

Q&A

解決済

1回答

466閲覧

hasManyで定義したリレーション先にアクセスできない

n18marron

総合スコア3

Laravel

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

0グッド

0クリップ

投稿2021/07/26 05:56

前提・実現したいこと

https://teratail.com/questions/350645
蔵書管理システムを作っています。

他人が借りた本は借りれないようにしたいです。
そのために該当idを条件にしてリレーション先のlendingsテーブルのidで降順のソートをかけて最新データ1件を取得して、viewファイルでstatusを表示したいです。

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

Property [lendings] does not exist on this collection instance.

またorderByが機能していません

// dd($datas)をすると↓ Illuminate\Database\Eloquent\Collection {#1251 ▼ #items: array:1 [▼ 0 => App\Models\Book {#1004 ▼ #table: "books" #fillable: array:1 [▶] +timestamps: false #connection: "sqlite" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] +preventsLazyLoading: false #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:2 [▼ "id" => "1" "title" => "title1" ] #original: array:2 [▶] #changes: [] #casts: [] #classCastCache: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: array:1 [▼ "lendings" => Illuminate\Database\Eloquent\Collection {#1254 ▼ #items: array:2 [▼ 0 => App\Models\Lending {#1258 ▼ #table: "lendings" #fillable: array:5 [▶] +timestamps: false #connection: "sqlite" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] +preventsLazyLoading: false #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:6 [▼ "id" => "1" "user_id" => "1" "book_id" => "1" "lent_date" => "2021-07-21 13:24:58" "return_date" => "2021-07-21 13:40:47" "status" => "0" ] #original: array:6 [▶] #changes: [] #casts: [] #classCastCache: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: [] #touches: [] #hidden: [] #visible: [] #guarded: array:1 [▶] } 1 => App\Models\Lending {#1260 ▼ #table: "lendings" #fillable: array:5 [▶] +timestamps: false #connection: "sqlite" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] +preventsLazyLoading: false #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:6 [▼ "id" => "4" "user_id" => "1" "book_id" => "1" "lent_date" => "2021-07-26 03:05:20" "return_date" => null "status" => "1" ] #original: array:6 [▶] #changes: [] #casts: [] #classCastCache: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: [] #touches: [] #hidden: [] #visible: [] #guarded: array:1 [▶] } ] } ] #touches: [] #hidden: [] #visible: [] #guarded: array:1 [▶] } ] }

該当のソースコード

コントローラ

// app\Http\Controllers\BookController.php public function edit(Request $request) { $id = $request->id; $datas = Book::where('id', $request->id) ->with('lendings') ->orderBy('id', 'desc') ->get(); // ->first(); あとで↑のgetとfirstを入れ替えます return view('books.edit', ['datas' => $datas]); }

ビュー

// resources\views\books\edit.blade.php @extends('layouts.app') @section('content') {{$datas->lendings->status}} <form action="" method="post"> @csrf <input name="title" type="text" value="{{ $datas->title }}"> <input type="submit" value="更新する"> </form> <form action="" method="post"> @csrf @method('delete') <input type="submit" value="削除"> </form> <form action="/lendings/lent" method="post"> @csrf <input name="book_id" type="hidden" value="{{ $datas->id }}"> <input type="submit" value="借りる"> </form> <form action="/lendings/return" method="post"> @csrf <input name="book_id" type="hidden" value="{{ $datas->id }}"> <input type="submit" value="返却する"> </form> @endsection

モデル

// app\Models\Book.php <?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); } public function getData() { $datas = [ 'id' => $this->id, 'title' => $this->title, ]; return $datas; } }
// app\Models\Lending.php <?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, 'user_id'); } public function book() { return $this->belongsTo(Book::class, 'book_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; } }

マイグレーション

// lendingsテーブル 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'); }); // booksテーブル Schema::create('books', function (Blueprint $table) { $table->increments('id'); $table->string('title'); });

試したこと

貸出履歴は該当の本の最新のデータを見ればよいのでhasOneでリレーションを作ってみましたがstatusにアクセスできませんでした

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

ここにより詳細な情報を記載してください。

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

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

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

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

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

AbeTakashi

2021/07/26 11:07

完全にソースコードを追い切れてないのでこれが原因じゃないかもしれませんが、hasmanyやblongtoの第2引数(や第3引数)は省略せずにちゃんと書いた方が良いと思います。 参考) https://qiita.com/mtakehara21/items/3cef9d12869d162e1ce9 Eloqunetでは リレーションメソッド名 + _idのサフィックスをつけたものをデフォルトの外部キーにしているため、 外部キーが異なる場合はメソッドの第2引数にカスタムキー名を渡す必要がある。 --- 省略できるのはテーブル名とカラム名が上手くマッチしている場合だけです。
guest

回答1

0

ベストアンサー

php

1 public function lendings() 2 { 3 return $this->hasMany(Lending::class, 'book_id', 'id') 4 ->orderBy('lengings.lent_date', 'desc'); 5 }

かな?

投稿2021/09/30 23:24

退会済みユーザー

退会済みユーザー

総合スコア0

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問