簡體   English   中英

Laravel雄辯地返回條件所在

[英]Laravel eloquent return both where conditions

您好,我有一個表格ideas ,我想返回user_id =帶有經過身份驗證的用戶ID的行,再加上category_id =假設為array [1, 2, 3]

免責聲明:我希望同時退回所有條件!

似乎是這樣:我認為您的表ideas和與之相關的模型創意具有下一個結構:id,user_id,category_id和其他一些字段...

要獲得認證用戶,可以執行Auth :: user();。 因此,您可以執行以下操作:

$categoryIds = [1, 2, 3];
$authUserId = Auth::user()->id;

$ideas = Idea::where('user_id', $authUserId)->whereIn('category_id', $categoryIds)->get();

如果需要通過查詢提取關系,則可以添加with語句:

$ideas = Idea::with('categories')->where('user_id', $authUserId)->whereIn('category_id', $categoryIds)->get();

ofc,您需要在模型中設置現實

您還可以在用戶模型中設置關系並獲取與用戶關聯的記錄:

User.php

public function ideas() {
    return $this->hasMany('App\Idea');
}

somewhere in code:

$categoryIds = [1, 2, 3];
Auth()->user()->ideas()->whereIn('category_id', $categoryIds)->get();

更新:要進行某種形式的聯接,可以使用以下命令:

$userIdeas = Idea::where('user_id', Auth::user()->id)->get();
$categoryIds = [1, 2, 3];
$categoryIdeas = Idea::where('user_id', '<>', Auth::user()->id)->whereId('category_id', $categoryIds)->get();
$mergedIdeas = $userIdeas->merge($categoryIdeas);

最后。 要在一個查詢中執行此操作:

$userId = Auth::user()->id;
$categoryIds = [1, 2, 3];
$ideas = Idea::where('user_id', $userId)->orWhere(function($query) use ($categoryIds) {
    $query->where('user_id', '<>', $userId)->whereIn('category_id', $categoryIds);
})->get();

我在知道想要什么時遇到了問題,但是

如果您希望獲得經過身份驗證的用戶ID和類別ID的結果,則可以

$category_ids = [1, 2, 3];
$model->where('category_id', auth()->user->id)->whereIn('user_id', $ids)->get();

如果您想要獲得經過身份驗證的用戶或數組中category_ids的結果,則可以

$category_ids = [1,2,3];
$model->orWhere(function($q) use($category_ids) {
    $q->where('category_id', auth()->user->id);
    $q->whereIn('user_id', $category_ids);
})->get();

請注意,如果未對用戶進行身份驗證,則此操作會中斷,但我將其留給您執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM