gpt4 book ai didi

php - Laravel Eloquent 关系不检索结果

转载 作者:行者123 更新时间:2023-11-29 05:54:29 25 4
gpt4 key购买 nike

我正在尝试使 laravel(5.6) 的表关系变得 Eloquent 。而且我无法从模型中检索关系表结果。下面我提到了这种关系。

关系:项目有一个类别

这是我的元素模型

class InventoryItems extends Model
{
/**
* table row delete
*/
use SoftDeletes;

/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'inventory_items';

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = ['id'];

protected $fillable = ['name','type_id','category_id','sub_category_id','description','cost_price','sale_price','image_path','image','store_id','status'];


public function category()
{
return $this->belongsTo('App\ItemCategories', 'id', 'category_id');
}
}

这是我的类别模型

class ItemCategories extends Model
{
/**
* table row delete
*/
use SoftDeletes;

/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'item_categories';

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = ['id'];

protected $fillable = ['name'];
}

这是我的 Controller

 public function index(Request $request)
{
$items = InventoryItems::all();

dd($items);

}

这是结果

Collection {#722 ▼
#items: array:2 [▼
0 => InventoryItems {#719 ▼
#table: "inventory_items"
#guarded: array:1 [▶]
#fillable: array:11 [▼
0 => "name"
1 => "type_id"
2 => "category_id"
3 => "sub_category_id"
4 => "description"
5 => "cost_price"
6 => "sale_price"
7 => "image_path"
8 => "image"
9 => "store_id"
10 => "status"
]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:15 [▼
"id" => 1
"name" => "Dell Keyboard"
"type_id" => 1
"category_id" => 1
"sub_category_id" => 1
"description" => "<p>test key</p>"
"cost_price" => 100.0
"sale_price" => 500.0
"image_path" => null
"image" => null
"store_id" => 1
"status" => 1
"created_at" => "2018-06-02 14:31:32"
"updated_at" => "2018-06-02 14:31:32"
"deleted_at" => null
]
#original: array:15 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#forceDeleting: false
}

我是 Eloquent 关系的新手,我引用了 laravel 文档和其他一些教程,但没有成功。一定是个愚蠢的错误想法。

最佳答案

首先,尝试向你的 Controller 添加with('category'),这样eloquent就知道你在调用关系。所以你的 Controller 应该看起来像

public function index(Request $request)
{
$items = InventoryItems::with('category')->get();

dd($items);

}

其次,我认为关系外键的顺序是错误的,应该是

return $this->belongsTo('YourModel','foreing_key','other_model_key')

所以你们的关系应该是这样的

return $this->belongsTo('App\ItemCategories', 'category_id', 'id');

关于php - Laravel Eloquent 关系不检索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51002782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com