[英]Laravel - Eloquent Relationship not working One to Many relationship
我有兩個具有一對多關系的模型。 我想在刀片中顯示具有關系的數據。
產品表
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' 未找到
似乎有時您有App
,有時有APP
,而 PHP 對類名不區分大小寫,您可能會使用在文件名方面區分大小寫的操作系統(Linux?)。
我建議到處都只有App
,您的錯誤消息清楚地表明: APP
。
您可以在模型文件中清楚地看到namespace
寫為“ namespace App;
”,您定義了應用程序文件夾的namespace
。 所以當你在任何地方使用這個模型時,你需要按照你定義的namespace
來編寫它。 因此“ App\\categoryModel
”。 您的代碼應如下所示:
public function category()
{
# code...
return $this->belongsTo('App\categoryModel','cat_id');
}
同樣真誠的請求,正如@alithedeveloper 提到的,請遵循 PSR 標准編寫代碼。
public function category()
{
return $this->belongsTo(abcModel::class,'cat_id');
}
public function products()
{
return $this->hasMany(productsModel::class,'cat_id');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.