如何使用 Laravel 从函数中的模型获取数据

How to Get Data From Model in Function With Laravel

是否可以在函数中从模型中获取数据?我想从产品模型中获取 SupplierID 数据。

public function productAjax($id)
{
    $product = new Producttext();
    $products = $product->productexts($id);
    $hitung_products = $products->count();

    $suplierproduct = Company::select('id', 'CompanyName')
        ->where(['id' => $products->SupplierID])
        ->first();
}

但是,在执行时,出现以下错误。

Property [SupplierID] does not exist on this collection instance.

如果您有产品文本 ID 那么

$product = Producttext::find($id)

$product = Producttext::where('id',$id)->first();


//test and check that you have it $product->SupplierID

$suplierproduct = Company::select('id', 'CompanyName')->where('id',$product->SupplierID)
->first();

你应该试试这个:

public function productajax($id)
{
    $products = Producttext::where('id',$id)->first();

    $suplierproduct = Company::select('id', 'CompanyName')
    ->where(['id' => $products->SupplierID])
    ->first();
}