0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel リレーション先へのアクセス方法の違い

Posted at

はじめに

PHP及びLaravelの勉強中。
基本的な部分だけどきちんと理解せずフワッと使用してるのでアウトプットしてみる。

設定

  • CategoryモデルとItemモデルが1対多の関係性で存在
    • Categoryモデル側 -> hasMany
    • Itemモデル側 -> belongsTo
// $categoryの中身
$category = Category::query()->find(1);

プロパティアクセス

$category->items;
=> Illuminate\Database\Eloquent\Collection

返り値はCollectionクラス。foreachで回してEloquentモデルの利用ができる。

メソッドアクセス

$category->items();
=> Illuminate\Database\Eloquent\Relations\HasMany

返り値はHasManyクラス。さらにメソッドを呼んで色々できる。

$category->items()->get();
=> Illuminate\Database\Eloquent\Collection

getメソッド呼べばプロパティアクセスと同様にCollectionが返る。

$category->items()->where('id',1)->first();
=> Illuminate\Database\Eloquent

特定のEloquentモデルを得ることもできる。
他にも色々。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?