ChrisF79
10 months ago

Need help with eloquent one to many relationship

Posted 10 months ago by ChrisF79

I'm trying to pull from a separate wordpress database (and it is working). However, I have a page that is just doing a var_dump of a post and that works because it is pulling from the wp_posts table wtih this model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $connection = 'wordpress';
    protected $table = 'wp_posts';

    public function postmeta()
    {
        return $this->hasMany(PostMeta::getMeta, 'post_id', 'ID');
    }
    
}

I want to pull the wp_postmeta data that shoudl go with the post.

wp_post has key of ID. wp_postmeta has key of post_id.

I have for the PostMeta model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class PostMeta extends Model
{
    protected $connection = 'wordpress';
    protected $table = 'wp_postmeta';

    public function getMeta()
    {
        return $this->belongsTo(Post::postmeta, 'ID', 'post_id');
    }
}

Then the controller simply does:

    public function index()
    {
        $posts = Post::first();
        return view('posts.index', compact('posts'));
    }

View:

    <?php print_r ($posts); ?>

That's just so I can test.

**My question is: ** Why isn't it pulling in the wp_postmeta fields automatically? Do I have something reversed?

Please sign in or create an account to participate in this conversation.