iT邦幫忙

0

Laravel Eloquent ORM問題

觀看Laravel Eloquent: 關聯文章時候
https://docs.laravel-dojo.com/laravel/5.5/eloquent-relationships#one-to-one

**我們可以使用 Eloquent 的動態屬性來取得關聯的記錄。動態屬性可以讓你存取關聯方法,這就像是在模型上定義它們的屬性一樣:

這邊有點疑惑**

使用了以下做法測試

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
	protected $table = "user";
    //key不設定為預設的id,使用uid
    protected $primaryKey = "uid";

    public function account()
    {
        return $this->hasMany('App\Models\UserAccount','user_id','uid');
    }
}
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserAccount extends Model
{
    protected $table = "user_accounts";
}

在使用以下方法進行時候有點疑問,為啥一定要用find()方法,才能使用->account呢?

測試用:

//這樣可以
$account = \App\Models\User::find(1)->account;

//這樣不行 顯示Property [account] does not exist on this collection instance.
$account = \App\Models\User::where('uid',1)->get()->account;

//這樣不行 顯示Property [account] does not exist on this collection instance.
$account = \App\Models\User::all()->account;

//這樣不行 顯示Method account does not exist.
$account = \App\Models\User::where('uid',1)->get()->account();

-------------------------------分隔線----------------------------------

//不使用關聯方法,單純搜尋一個表資料,都是正常的。

//找ID 正常
$account = \App\Models\User::find(1);
$account = \App\Models\User::where('uid',1)->get();
//找all 正常
$account = \App\Models\User::all();
$account = \App\Models\User::get();
weiclin iT邦高手 4 級 ‧ 2018-08-30 07:00:32 檢舉
因為 find 傳回單一資料, get 或 all 傳回 collection
weiclin iT邦高手 4 級 ‧ 2018-08-30 07:02:26 檢舉
說明在這邊
https://docs.laravel-dojo.com/laravel/5.5/eloquent
嘗試了一下用dd find回傳了{ data},get.all回傳了Collection[{data}]
所以回傳單一資料的情況下,看來才能使用這種做法。
感謝。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答