如何写远程一对多反向?

文档中只说明 远程一对多 使用

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    /**
     * 当前国家所有文章
     */
    public function posts()
    {
        return $this->hasManyThrough('App\Models\Post', 'App\Models\User');
    }
}

这是文档

https://learnku.com/docs/laravel/8.x/eloquent-relationships/9407#has-many-through

那么反向改如何写? 想知道 这篇文章属于那个国家的?

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

反向就是hasOneThrough关联,调整好几个参数对应的字段,就能关联出来了

3年前 评论
讨论数量: 4

$post->user->country

4年前 评论

反向就是hasOneThrough关联,调整好几个参数对应的字段,就能关联出来了

3年前 评论
德国科隆街头的大胡子

hasOneThrough后面的四个参数反着写

3年前 评论
/**
     * 关联楼宇推荐书关联表
     * 远程一对一
     */
    public function buildingPanos()
    {
        return $this->hasManyThrough(
            'App\Building',                // 远程表
            'App\ModelList\BuildingPano',  // 中间表
            'pano_id',                     // 中间表对主表的关联字段
            'id',                          // 远程表对中间表的关联字段
            'pano_config_id',              // 主表对中间表的关联字段
            'building_id'                  // 中间表对远程表的关联字段
        );
    }

反过来, 这个比文档看着易懂, 借个楼记录下 :joy:

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!