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"}}
原文地址:https://www.cnblogs.com/songyongzhan/p/12250012.html