作为程序员一定要保持良好的睡眠,才能好编程

laravel 关联模型中withDefault方法的作用

发布时间:2020-02-01


withDefault 方法为什么会存在?


laravel提供了非常好用的关联模型使用,正常情况下 文章对应的添加用户是存在的,如果用户表中的数据删除,那么关联模型就会返回一个null值。


就是为了解决返回null所带来问题的。


举例说明:


在没有使用withDefault方法时候:


PostsModel.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PostsModel extends Model
{

    protected $table = 'posts';

    protected $guarded = [];

    //获取用户
    public function user()
    {
        return $this->belongsTo(UserModel::class, 'user_id', 'id');
    }

}


新闻表:

image.png

用户表

image.png


image.png



使用withDefault方法后:


PostsModel.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PostsModel extends Model
{

    protected $table = 'posts';

    protected $guarded = [];

    //获取用户
    public function user()
    {
        return $this->belongsTo(UserModel::class, 'user_id', 'id')->withDefault();
     }

}


使用了 withDefault 方法以后,就会返回空对象


image.png



当使用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":[]}


当然还可以传递一个默认数组,当差找不到数据的时候,直接放默认设置的数据返回:


image.png

{"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"}}