Laravel 7 Eloquent 人际关系无效
Laravel 7 Eloquent relationships not working
我正在使用 laravel 7。我有 2 个表、产品和推荐书。每个推荐都与产品相关。所以我建立了两个关系:
- 产品:hasMany('App\Models\OM\Testimonial');
- 见证:belongsTo('App\Models\OM\Product', 'product_id')
但是当我 dd(Testimonial->with('product)) 我得到这个
array:1 [▼ "testimonials" => Illuminate\Database\Eloquent\Builder
{#347 ▼
#query: Illuminate\Database\Query\Builder {#358 ▶}
#model: App\Models\OM\Testimonial {#359 ▼
#table: "om_testimonials"
#fillable: array:4 [▶]
#connection: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
#eagerLoad: array:1 [▶]
#localMacros: []
#onDelete: null
#passthru: array:19 [▶]
#scopes: []
#removedScopes: [] } ]
这很正常,with
要求 Eloquent 预先加载您的关系,但它尚未检索它,因为它允许您在 "query" 上添加约束。您需要这样做来检索您的模型及其关系
Testimonial::with('product')->get();
您还应该查看文档,每个细节都在这里:https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
我正在使用 laravel 7。我有 2 个表、产品和推荐书。每个推荐都与产品相关。所以我建立了两个关系:
- 产品:hasMany('App\Models\OM\Testimonial');
- 见证:belongsTo('App\Models\OM\Product', 'product_id')
但是当我 dd(Testimonial->with('product)) 我得到这个
array:1 [▼ "testimonials" => Illuminate\Database\Eloquent\Builder {#347 ▼ #query: Illuminate\Database\Query\Builder {#358 ▶} #model: App\Models\OM\Testimonial {#359 ▼ #table: "om_testimonials" #fillable: array:4 [▶] #connection: null #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: false +wasRecentlyCreated: false #attributes: [] #original: [] #changes: [] #casts: [] #classCastCache: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: [] #touches: [] +timestamps: true #hidden: [] #visible: [] #guarded: array:1 [▶] } #eagerLoad: array:1 [▶] #localMacros: [] #onDelete: null #passthru: array:19 [▶] #scopes: [] #removedScopes: [] } ]
这很正常,with
要求 Eloquent 预先加载您的关系,但它尚未检索它,因为它允许您在 "query" 上添加约束。您需要这样做来检索您的模型及其关系
Testimonial::with('product')->get();
您还应该查看文档,每个细节都在这里:https://laravel.com/docs/7.x/eloquent-relationships#eager-loading