觀看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();