Misc / Many-to-Many Relationships

Fieldmanager can assist you in creating many-to-many relationships between posts using the $reciprocal property of Fieldmanager_Datasource_Post and the $serialize_data property of Fieldmanager_Field.

Note that this only works using Fieldmanager_Datasource_Post and Fieldmanager_Datasource_User as of this writing. Support for Fieldmanager_Datasource_Term is outstanding.

  1. Example 1: Many-to-Many Relationship

    For this example, imagine a site maintaining a database of actors and movies. For the most part, movies have many actors, and actors are in many movies. Here is how we might structure our fields to assist with this many-to-many relationship.

    add_action( 'init', function () {
    	register_post_type( 'actor', [
    		'public'   => true,
    		'supports' => [ 'title' ],
    		'label'    => 'Actors',
    	] );
    	register_post_type( 'movie', [
    		'public'   => true,
    		'supports' => [ 'title' ],
    		'label'    => 'Movies',
    	] );
    } );
    
    add_action( 'fm_post_actor', function ( $post_type ) {
    	( new Fieldmanager_Autocomplete(
    		[
    			'name'           => 'movies',
    			'limit'          => 0,
    			'sortable'       => true,
    			'serialize_data' => false,
    			'datasource'     => new Fieldmanager_Datasource_Post(
    				[
    					'reciprocal' => 'actors',
    					'query_args' => [ 'post_type' => 'movie' ],
    				]
    			),
    		]
    	) )->add_meta_box( 'Movies', $post_type );
    } );
    
    add_action( 'fm_post_movie', function ( $post_type ) {
    	( new Fieldmanager_Autocomplete(
    		[
    			'name'           => 'actors',
    			'limit'          => 0,
    			'sortable'       => true,
    			'serialize_data' => false,
    			'datasource'     => new Fieldmanager_Datasource_Post(
    				[
    					'reciprocal' => 'movies',
    					'query_args' => [ 'post_type' => 'actor' ],
    				]
    			),
    		]
    	) )->add_meta_box( 'Actors', $post_type );
    } );