简体   繁体   中英

Laravel 7 Eloquent relationships not working

Im am using laravel 7. I have 2 tables, products and testimonials. Each testimonial is related to a product. So i made an 2 relationships:

  • Product: hasMany('App\Models\OM\Testimonial');
  • Testimonial: belongsTo('App\Models\OM\Product', 'product_id')

But when i dd(Testimonial->with('product)) i get this

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: [] } ]

It's normal, with asks Eloquent for eager-loading your relationship but it does not retrieve it yet because it allows you to add constraints on your "query". You need to do this to retrieve your models and their relationship

Testimonial::with('product')->get();

You should also check the documentation, every detail is here: https://laravel.com/docs/7.x/eloquent-relationships#eager-loading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM