corcel / acf

Advanced Custom Fields (ACF) plugin for Corcel
128 stars 100 forks source link

PostObject.php incorrectly binding the parent post_type #6

Closed cjke closed 7 years ago

cjke commented 7 years ago

Lets say we have two post types - Movie + Genre. Where Movie has a "Relationship" to Genre.

If you do the following:

Movie::find(1)->acf->genre

It will always return an empty collection.

This is because the query in PostObject is using the passed in model $post (which is the parent object) and using that as the base query (which is binding the parent post type instead of the child post type).

//  PostObject.php
public function process($fieldName)
{
    $postId = $this->fetchValue($fieldName);

    if (is_array($postId)) {

        var_dump($this->post->whereIn('ID', $postId)->toSql());
        var_dump($this->post->whereIn('ID', $postId)->getBindings());
        // select * from `wp_posts` where `post_type` = ? and `ID` in (?)
        // ?1: movie (should be genre, or nothing)
        // ?2: 304

        $this->object = $this->post->whereIn('ID', $postId)->get();
    } else {
        $this->object = $this->post->find($postId);
    }
}

I think, PostObject is done this way for the other two cases (post and post_object), but I think it might need to be split out - so perhaps a RelationshipObject.php.

Like the other issues can do a PR if needed

jgrossi commented 7 years ago

@cjke sure thing! can you send a PR and make sure all the phpunit tests are passing? if so can you add one more test for this specific issue? thanks! JG

cjke commented 7 years ago

Will do.

Can I ask, with your test bootstrap, do you already have a running instance of WP loaded with the .sql included in the repo? Or do you have something like docker that auto-spins up during a test cycle?

jgrossi commented 7 years ago

@cjke for tests you don't actually need a WP install, just using the SQL dump to a MySQL database. If you want to change the database, adding posts, metadata, etc, I suggest you to have a local WP install pointing to the same database.

cjke commented 7 years ago

Cool no worries, thanks for the clarification.

cjke commented 7 years ago

This is already fixed in dev! Whoops. You are now passing in $post directly to the process method, so it's not adding this clause post_type = ? anymore, which is perfect.