withDefault 方法為什么會存在?
laravel提供了非常好用的關聯模型使用,正常情況下 文章對應的添加用戶是存在的,如果用戶表中的數據刪除,那么關聯模型就會返回一個null值。
就是為了解決返回null所帶來問題的。
舉例說明:
在沒有使用withDefault方法時候:
1 <?php 2 3 namespace App; 4 5 use Illuminate\Database\Eloquent\Model; 6 7 class PostsModel extends Model 8 { 9 10 protected $table = 'posts'; 11 12 protected $guarded = []; 13 14 //獲取用戶 15 public function user() 16 { 17 return $this->belongsTo(UserModel::class, 'user_id', 'id'); 18 } 19 20 }
使用withDefault方法后:
PostsModel.php
1 <?php 2 3 namespace App; 4 5 use Illuminate\Database\Eloquent\Model; 6 7 class PostsModel extends Model 8 { 9 10 protected $table = 'posts'; 11 12 protected $guarded = []; 13 14 //獲取用戶 15 public function user() 16 { 17 return $this->belongsTo(UserModel::class, 'user_id', 'id')->withDefault(); 18 } 19 20 }
使用了 withDefault 方法以后,就會返回空對象
當使用json_encode($posts); 方法后,就會得到下面的結果:
空數組
{"id":3,"title":"test008","content":"test content","user_id":8,"created_at":"2020-02-01 15:31:21","updated_at":"2020-02-01 15:31:21","user":[]}
當然還可以傳遞一個默認數組,當差找不到數據的時候,直接放默認設置的數據返回:
{"id":3,"title":"test008","content":"test content","user_id":8,"created_at":"2020-02-01 15:31:21","updated_at":"2020-02-01 15:31:21","user":{"nam
e":"wangwu"}}
以上就是withDeafult 方法的使用。
如果數據找到,則正常返回
$posts = PostsModel::query()->with('user')->find(1);
{"id":1,"title":"test001","content":"test content","user_id":1,"created_at":"2020-02-01 15:16:05","updated_at":"2020-02-01 15:16:05","user":{"id"
:1,"name":"james","updated_at":"2020-02-01 15:25:08","created_at":"2020-02-01 15:25:08"}}