Dosmukhanbet
1 month ago

Get belongstomany if contains only given ids

Posted 1 month ago by Dosmukhanbet

Hello, Please kindly assist me with making query that will return instance Route model if contains only both given ids.

I have Route and Point model, they are linked with 'point_route' table - Many to Many Relationship.

Goal is take route that contain given both 2 point ids.

For example given ids 1 and 2, the query should return Route that has both given ids , considering below table example it should return Route with id 1.


point_id	route_id	
1	           1	
2	           1	
2	           2	
3	           2
4		   2

class Route extends Model
{

    public function points()
    {
        return $this->belongsToMany(Point::class)->withPivot('point_order');
    }
    
    public function pointsIds()
    {
        return $this->points()->pluck('point_id');
    }

}

//
web.php
use App\Route as Routes;

Route::get('test', function () {

    $pointIds = [1, 2];

    $route = Routes::find(1);

    dd($route->pointsIds()->has($pointIds));

});

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