簡體   English   中英

通過 arguments inside API 資源調用 in Laravel

[英]Pass arguments inside API resource call in Laravel

我正在嘗試使用 Laravel 中的邏輯分組檢索記錄。我在 API 資源中執行此操作。

我想要的是?

我想在 API 資源 function 中傳遞 arguments 並在 where 條件下使用該值。 例如: Address::where(function($q1) use (somevalue)

我做了什么

我嘗試使用以下代碼。

public function toArray($request)
{
    return [
        'name'   => $this->name,
        'domain' => $this->domain,
        'addresses' => AddressResource::collection(Address::where(function($q1) use ($this->company_id){
                $q1->where('company_id', $this->company_id);
            })
            ->where(function($q2) {
                $q2->where('is_shipping', 1)
                    ->orWhere('is_billing', 1);
            })
            ->get()),
    ];
}

但是這里的問題是$this->company_id無法傳遞。 它只接受 static 值,如abc但不接受上面的$this->company_id

我得到的錯誤

syntax error, unexpected token \"->\", expecting \")\"

(注: 'addresses' => AddressResource::coll......是第27行)

我怎樣才能做到這一點? 任何線索將不勝感激。

你可以試試這個

public function toArray($request)
{
    $company_id = $this->company_id;
    return [
        'name'   => $this->name,
        'domain' => $this->domain,
        'addresses' => AddressResource::collection(Address::where(function($q1) use ($company_id){
            $q1->where('company_id', $company_id);
        })
            ->where(function($q2) {
                $q2->where('is_shipping', 1)
                    ->orWhere('is_billing', 1);
            })
            ->get()),
    ];
}

不能直接通過。 取一個 Var abc 並存儲你的值 $abc = $this->company_id; 然后傳遞給閉包函數。 我希望這會奏效

暫無
暫無

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

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