如何写远程一对多反向?

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

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

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

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
最佳答案

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

2年前 评论
讨论数量: 4

$post->user->country

3年前 评论

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

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

hasOneThrough后面的四个参数反着写

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

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

2年前 评论

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