目前我在 MySQL 中有 3 個表(視頻、關鍵字、video_keywords)。video_keywords是一個樞軸形式的視頻和關鍵字(id, keyword_id, video_id)。主要問題是:如何從 pivotParent(關鍵字表中的名稱表)接收數據?目前我只能從表中獲取keyword_id,video_id從video_keywords表中獲取所有數據,videos但我無法從keywords表中獲取任何內容$keyword->videos 的轉儲keywords/list.blade.php給出輸出:[{"id":4,"youtube_id":"cq2Ef6rvL6g","title":"AMBIENT CHILLOUT LOUNGE RELAXING MUSIC - Essential Relax Session 1 - Background Chill Out Music -","created_at":"2020-01-22 14:39:41","updated_at":"2020-01-22 14:39:41","pivot":{"keyword_id":"5","video_id":"4"}}] #items: array:1 [▼ 0 => App\Models\Video {#390 ▼ #fillable: array:2 [?] #connection: "mysql" #table: "videos" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:5 [?] #original: array:7 [?] #changes: [] #casts: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: array:1 [▼ "pivot" => Illuminate\Database\Eloquent\Relations\Pivot {#391 ▼ #guarded: [] #connection: "mysql" #table: "video_keywords" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:2 [?] #original: array:2 [?] #changes: [] #casts: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: [] #touches: [] +timestamps: false #hidden: [] #visible: [] #fillable: [] +pivotParent: App\Models\Keyword {#356 ▼ #fillable: array:1 [?] #connection: "mysql"
1 回答

不負相思意
TA貢獻1777條經驗 獲得超10個贊
返回一個的BelongsToMany實例Illuminate\Database\Eloquent\Collection,它是關鍵字視頻的列表。
因此,您可以像這樣檢索第一個視頻的名稱:
dump($keyword->videos->first()->name);
或者,如果您想循環瀏覽視頻列表:
foreach ($keyword->videos as $video) {
dump($video->name);
}
您可以在此處閱讀有關多對多關系的更多信息:https ://laravel.com/docs/6.x/eloquent-relationships#many-to-many
- 1 回答
- 0 關注
- 131 瀏覽
添加回答
舉報
0/150
提交
取消