我的表格(Mysql):
行动者:
CREATE TABLE `actors` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`active` tinyint(1) NOT NULL
);
影:
CREATE TABLE `movies` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL
);
Actor_Movie:
CREATE TABLE `actor_movie` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`actor_id` int(10) unsigned NOT NULL,
`movie_id` int(10) unsigned NOT NULL,
KEY `actor_movie_actor_id_foreign` (`actor_id`),
KEY `actor_movie_movie_id_foreign` (`movie_id`),
CONSTRAINT `actor_movie_actor_id_foreign` FOREIGN KEY (`actor_id`)
REFERENCES `actors` (`id`) ON DELETE CASCADE,
CONSTRAINT `actor_movie_movie_id_foreign` FOREIGN KEY (`movie_id`)
REFERENCES `movies` (`id`) ON DELETE CASCADE
);
电影模特:
...
public function actors() {
return $this->belongsToMany('App\Actor');
}
演员模特:
...
public function movies() {
return $this->belongsToMany('App\Movie');
}
使用演员获取电影的实际查询:
$movies = Movie::with('actors')->get();
结果为JSON:
movies: [{
id: 1,
name: 'movie1',
actors: [{ id: 1, name: 'actor1' }, { id: 2, name: 'actor2' }]
}, {
id: 2,
name: 'movie2',
actors: [{ id: 1, name: 'actor1' }, { id: 3, name: 'actor3' }]
}...]
任何解决方案都可以使用Laravel集合或Mysql查询来与他们的演员一起获得多部电影。通过上面的查询,我得到每部电影的演员,但我想获得多部电影/演员,例如,第一张唱片将是演员1和演员2扮演同一部电影movie1和movie2等。
['movie1', 'movie2'] => ['actor1', 'actor2']
['movie1', 'movie3'] => ['actor1', 'actor3']
['movie4', 'movie5', 'movie6'] => ['actor4"]
etc...
谢谢。