![](/img/trans.png)
[英]Laravel how to return the value NULL when hasMany relationship is empty
[英]Laravel hasMany return null
我有型號分類:
class Category extends Model
{
protected $fillable = ['title', 'description', 'keywords', 'slug'];
public function getRouteKeyName()
{
return 'slug';
}
public function products()
{
return $this->hasMany(Product::class);
}
}
並有型號產品:
class Product extends Model
{
protected $guarded = [];
public function category()
{
return $this->belongsTo(Category::class);
}
}
在表格產品中,我的產品category_id
。 但是返回null。 為什么? 我無法使用$category->products
獲得當前類別的$category->products
,因為它總是空的。 我怎么解決這個問題?
在模型產品關系category
工作中,但在模型category
不工作..
在桌面產品我有級聯:
$table->foreign('category_id')
->references('id')->on('categories')
->onDelete('cascade');
驗證您的定義
return $this->hasMany('App\Product', 'category_id');
你在這里有錯誤,因為附加在catergories但它將在產品上
$table->foreign('category_id')
->references('id')->on('products')
->onDelete('cascade');
https://laravel.com/docs/5.6/eloquent-relationships#querying-relations
一切都是正確的,只需在產品遷移中進行更改即可更改此代碼
$table->foreign('category_id')->references('id')
->on('categories')->onDelete('cascade');
至
$table->foreign('category_id')->references('id')
->on('products'->onDelete('cascade');
請進行以下更改
在產品遷移文件中進行更改(在產品表中)
$table->integer('category_id')->unsigned(); $table->foreign('category_id')->references('category_id')->on('categories');
然后更改類別模型
public function products() { return $this->hasMany('App\\Product','category_id'); }
3.然后獲得所有類別的產品清單
use App\Category
// include category model where you want to call this function
Category::with('products')->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.