Blade Query与多个where和orWhere子句匹配某些id

时间:2016-10-30 14:09:49

标签: php mysql laravel

我有一个laravel项目,我想检查用户是拥有者还是从MySQLDB租用属性,我有一个允许他们访问页面并编辑此属性的重写规则

Route::get('/housing/manage/{id}', function() {
        return view('pages.housing_management.housing_management');
    });

现在,我有这个查询,检查他们是拥有还是租用它,但那是为了检查是否有任何匹配该规则的属性,这是我可以确保他们拥有或租用属性的方式id =与页面一起发送的{id}?

@if (count(Properties::where('owner', '=', Auth::user()->id)->orWhere('rented_by', '=', Auth::user()->id)->orderBy('id', 'DESC')->limit(1)->get()) > 0)
<p>Authentication Passed, you either own or rent this property.</p>
@endif

2 个答案:

答案 0 :(得分:0)

您的查询可以用routes.php文件写成:

Route::get('/housing/manage/{id}', function($id) {
        $exists = Properties::where('id', '=', $id)
                            ->where(function($q) {
                                $q->where('owner', '=', Auth::user()->id)
                                    ->orWhere('rented_by', '=', Auth::user()->id);
                            })->exists()
        return view('pages.housing_management.housing_management', compact('exists'));
    });

在您的刀片文件中,您可以写为:

@if ($exists)
<p>Authentication Passed, you either own or rent this property.</p>
@endif

答案 1 :(得分:0)

我认为这种情况的最佳做法是在用户模型中向属性模型添加两个关系 - 像这样:

public function ownedProperties() {
    return $this->hasMany(Properties::class, 'owner');
}

public function rentedProperties() {
    return $this->hasMany(Properties::class, 'rented_by');
}

然后你的支票会是这样的:

@if ($user->ownedProperties->contains($propertyId) || $user->rentedProperties->contains($propertyId))
   <p>Authentication Passed, you either own or rent this property.</p>
@endif