简体   繁体   中英

Laravel Nova Model relationship 2 or more models

I'm using the Laravel Nova framework and I'm having difficulty using relationships when it comes to visualization (index, and show methods).

Ex: I have a model called User (id, name address_id), it has a relationship with Address (id, street, state_id), and Address has a relationship with State (id, name), all use belongsTo .

How do I show State in the User profile? The way I know of is $ user-> address-> state-> name , but how do I do that with Nova? Or would you have to create a state_id field in User as well? (that would be awful)

Nova support callbacks for field value description. Try this one:

Text::make('state', function($resource) {
                // Some code for receiving your state data
                return $resource->address->state; // as example
            })->exceptOnForms(),

For more details, read this Computed Fields

And this Dynamic Field Methods

You can use displayUsing

 BelongsTo::make('State name', 'address', Address::class)                      
       ->displayUsing(function () {
            return $this->address->state->name;
        })

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