我在商店项目中使用Laravel,我创建了模型
型号:Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function products(){
return $this->hasMany(Product::class);
}
}
型号:Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category(){
return $this->belongsTo(Category::class);
}
public function comments(){
return $this->hasMany(Comment::class);
}
}
控制器:ProductController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function getAll($idCategory)
{
$roducts = Category::findOrFail($idCategory)->products();
}
}
我收到此错误:
在\ App \ Category中找不到方法'findOrFail'
我试图通过更改为
来解决此问题 $roducts = Category::query()->findOrFail($idCategory)->products();
我得到了这个错误:
在\ Illuminate \ Database \ Eloquent \ Collection | \ Illuminate \ Database \ Eloquent \ Model | static | static []中找不到方法“产品”
更新 我正在使用Laravel 5.7.24,并且错误来自IDE(PhpStorm)。