无法通过 laravel5.6 中的自定义枢轴 table 获取多对多相关 table

Cannot make it work to get many to many related table by custom pivot table in laravel5.6

我的Post模型有这个功能不工作

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $table = "wp_posts";
    protected $primaryKey = "ID";

    public function taxonomies()
    {
        return $this->belongsToMany('App\Models\TermTaxonomy', 'wp_term_relationships', 'object_id', 'term_taxonomy_id');
    }
}

我想通过枢轴 table 从 post 获取分类法数据,但我做不到。

我将 Laravel 连接到我的 WP 数据库并尝试从 Post 中获取分类法。

Posts 和分类法与 'wp_term_relationships' 枢轴 table 存在多对多关系。

post table 有 'ID' 主键

分类法table有'term_taxonomy_id'个主键

支点table就像 'wp_term_relationships' - 'object_id' ... 与 Post.ID 有关 - 'term_taxonomy_id' ... 与 Taxonomy.term_taxonomy_id

有关

我不知道为什么这不起作用。如果有人知道请帮助我。非常感谢。

添加

// Taxonomy
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class TermTaxonomy extends Model
{
    protected $table = 'wp_term_taxonomy';
    protected $primaryKey = 'term_taxonomy_id';
}

// in the Controller
public function profile($id)
{
    $teacher = User::isTeacher()->where(['ID' => $id])->with(['posts' => function ($query) {
        $query->where('post_type', 'answer')->take(3);
    }])->firstOrFail();

    $data = [
        'teacher' => $teacher
    ];

    return view('teacher.profile', $data);
}

// in the View
@foreach($teacher->posts as $answer) 
    @php 
    foreach($answer->postParent->taxonomies as $taxonomy) { 
        print($taxonomy->term_id); 
    } 
    @endphp 
@endforeach

实际问题不是如何定义多对多关系, 就是如何检索关系数据。

public function profile($id)
{
    $teacher = User::isTeacher()->where(['ID' => $id])->with(['posts' => function ($query) {
        $query->where('post_type', 'answer')->take(3)->with(['postParent' => function ($query) {
            $query->where('post_type', 'question')->with(['taxonomies' => function ($query) {
                $query->where('taxonomy', 'question_category')->with(['term']);
            }]);
        }]);
    }])->firstOrFail();

    $data = [
        'teacher' => $teacher
    ];

    return view('teacher.profile', $data);
}