Laravel模型属于当前用户和全局用户

时间:2018-06-26 21:45:32

标签: php laravel

我有以下收藏:

用户

{
    "id": 1,
    "name": "Bob"
},
{
    "id": 2,
    "name": "Mary"
}

资料

{
    "id": 1,
    "user_id": 1,
    "name": "Bob's stuff"
},
{
    "id": 2,
    "user_id": 2,
    "name": "Mary's stuff"
},
{
    "id": 3,
    "user_id": 0,
    "name": "Everyone's stuff"
},
{
    "id": 4,
    "user_id": null,
    "name": "Global stuff"
}

...以及以下型号:

class User extends Eloquent {
    public function stuff() {
        return $this -> hasMany( 'Stuff' ) ;
    }
}
class Stuff extends Eloquent {
    public function user() {
        return $this -> belongsTo( 'User' ) ;
    }
}

如何自动将每个人的内容(User.id == 0)和全局内容(User.id == null)添加到每个人的模型中?换句话说,如果我要查询鲍勃的东西,我希望得到以下信息:

{
    "id": 1,
    "user_id": 1,
    "name": "Bob's stuff"
},
{
    "id": 3,
    "user_id": 0,
    "name": "Everyone's stuff"
},
{
    "id": 4,
    "user_id": null,
    "name": "Global stuff"
}

1 个答案:

答案 0 :(得分:2)

您可以使用此:

public function stuff() {
    return $this->hasMany(Stuff::class)->orWhere('user_id', 0)->orWhereNull('user_id');
}

缺点是您不能仅添加其他WHERE子句:

$user->stuff()->where('foo', 'bar')->get(); // Doesn't work as expected.

结果,无法立即加载。