gpt4 book ai didi

php - Laravel get() 与()

转载 作者:搜寻专家 更新时间:2023-10-30 22:29:30 24 4
gpt4 key购买 nike

Laravel 5.5。当我这样使用 Controller 时:

$ad = Ad::get();
$category = Category::get();
$categoryItem = CategoryItem::get();

$c = CategoryItem::with('ad')->get();

我得到这样的 View :

{"id":1,"ad_id":"1","cat_id":"1","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","ad":{"id":1,"title":"Test 1","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00"}}

{"id":2,"ad_id":"2","cat_id":"2","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","ad":{"id":2,"title":"Test 2","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00"}}

{"id":3,"ad_id":"3","cat_id":"1","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","ad":{"id":3,"title":"Test 3","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00"}}

{"id":4,"ad_id":"4","cat_id":"2","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","ad":{"id":4,"title":"Test 4","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00"}}

CategoryItem 模型属于 Ad 和 Category 类。

但是,当我尝试使用 Category 获取 CategoryItem 时,我的意思是这样的:

$ad = Ad::get();
$category = Category::get();
$categoryItem = CategoryItem::get();

$c = CategoryItem::with('category')->get();

我得到这个 View ,在 Category 对象旁边有 NULL:

{"id":1,"ad_id":"1","cat_id":"1","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","category":null}

{"id":2,"ad_id":"2","cat_id":"2","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","category":null}

{"id":3,"ad_id":"3","cat_id":"1","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","category":null}

{"id":4,"ad_id":"4","cat_id":"2","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","category":null}

类别模型有许多 Ads 和 CategoryItems。

我真正想做的是能够通过 CategoryItem 获取广告和类别、标题、ID 和其他信息...我只需要了解这一点,以便稍后可以将通过 id 获取项目更改为通过鼻涕虫名字...

最佳答案

由于您使用的是自定义外键名称 cat_id 而不是 category_id,要使您的代码正常工作,您需要在关系定义中指定外键:

public function category()
{
return $this->belongsTo(Category::class, 'cat_id');
}

Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. You may pass a custom key name as the second argument to the belongsTo method

https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse

关于php - Laravel get() 与(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46757404/

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