【发布时间】:2020-05-30 10:23:51
【问题描述】:
我有两个具有一对多关系的模型。我想在刀片中显示具有关系的数据。
产品表
Table name = Products
PrimaryKey = pro_id
ForeignKey = cat_id
类别表
Table name = categories
PrimaryKey = cat_id
产品型号代码
namespace App;
use Illuminate\Database\Eloquent\Model;
class productsModel extends Model
{
//code...
protected $table = 'products';
protected $primaryKey = 'pro_id';
// Every Products Belongs To One Category
public function category()
{
# code...
return $this->belongsTo('APP\abcModel','cat_id');
}
}
类别型号代码
namespace App;
use Illuminate\Database\Eloquent\Model;
class categoryModel extends Model
{
//code...
protected $table = 'categories';
protected $primaryKey = 'cat_id';
// One Category Has Many Products
public function products()
{
# code...
return $this->hasMany('App\productsModel','cat_id','pro_id');
}
}
控制器代码
命名空间 App\Http\Controllers;
use Illuminate\Http\Request;
use App\productsModel;
class productsController extends Controller
{
//code...
public function products($category_id='')
{
# code...
$data["products"] = productsModel::where
('cat_id',$category_id)
->get();
$data["categories"] = productsModel::where
('cat_id',$category_id)->first()->category;
echo "<pre>";
print_r($data);
echo "</pre>";
}
}
错误: Symfony\Component\Debug\Exception\FatalThrowableError 找不到类“APP\categoryModel”
【问题讨论】:
-
首先,您需要查看 PSR 标准以编写代码以及如何命名类
-
应用程序!=应用程序。命名空间不区分大小写。