@@ -38,6 +38,7 @@ protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
38
38
});
39
39
40
40
Schema::create ('users_posts ' , function (Blueprint $ table ) {
41
+ $ table ->increments ('id ' );
41
42
$ table ->string ('user_uuid ' );
42
43
$ table ->string ('post_uuid ' );
43
44
$ table ->tinyInteger ('is_draft ' )->default (1 );
@@ -932,6 +933,33 @@ public function testOrderByPivotMethod()
932
933
$ relationTag2 = $ post ->tagsWithCustomExtraPivot ()->orderByPivot ('flag ' , 'desc ' )->first ();
933
934
$ this ->assertEquals ($ relationTag2 ->getAttributes (), $ tag3 ->getAttributes ());
934
935
}
936
+
937
+ public function testFirstOrMethod ()
938
+ {
939
+ $ user1 = User::create (['name ' => Str::random ()]);
940
+ $ user2 = User::create (['name ' => Str::random ()]);
941
+ $ user3 = User::create (['name ' => Str::random ()]);
942
+ $ post1 = Post::create (['title ' => Str::random ()]);
943
+ $ post2 = Post::create (['title ' => Str::random ()]);
944
+ $ post3 = Post::create (['title ' => Str::random ()]);
945
+
946
+ $ user1 ->posts ()->sync ([$ post1 ->uuid , $ post2 ->uuid ]);
947
+ $ user2 ->posts ()->sync ([$ post1 ->uuid , $ post2 ->uuid ]);
948
+
949
+ $ this ->assertEquals (
950
+ $ post1 ->id ,
951
+ $ user2 ->posts ()->firstOr (function () {
952
+ return Post::create (['title ' => Str::random ()]);
953
+ })->id
954
+ );
955
+
956
+ $ this ->assertEquals (
957
+ $ post3 ->id ,
958
+ $ user3 ->posts ()->firstOr (function () use ($ post3 ) {
959
+ return $ post3 ;
960
+ })->id
961
+ );
962
+ }
935
963
}
936
964
937
965
class User extends Model
@@ -949,6 +977,13 @@ protected static function boot()
949
977
});
950
978
}
951
979
980
+ public function posts ()
981
+ {
982
+ return $ this ->belongsToMany (Post::class, 'users_posts ' , 'user_uuid ' , 'post_uuid ' , 'uuid ' , 'uuid ' )
983
+ ->withPivot ('is_draft ' )
984
+ ->withTimestamps ();
985
+ }
986
+
952
987
public function postsWithCustomPivot ()
953
988
{
954
989
return $ this ->belongsToMany (Post::class, 'users_posts ' , 'user_uuid ' , 'post_uuid ' , 'uuid ' , 'uuid ' )
@@ -974,6 +1009,13 @@ protected static function boot()
974
1009
});
975
1010
}
976
1011
1012
+ public function users ()
1013
+ {
1014
+ return $ this ->belongsToMany (User::class, 'users_posts ' , 'post_uuid ' , 'user_uuid ' , 'uuid ' , 'uuid ' )
1015
+ ->withPivot ('is_draft ' )
1016
+ ->withTimestamps ();
1017
+ }
1018
+
977
1019
public function tags ()
978
1020
{
979
1021
return $ this ->belongsToMany (Tag::class, 'posts_tags ' , 'post_id ' , 'tag_id ' )
0 commit comments