Reputation: 13
How can I send a value from Controller to Model and how to receive the value in the Model.
I let above a picture of my database tables.
Example: If I enter in the input 3 action movies
$category=category::with('film')->where('name','=','Action')->first();
Film model:3
class film extends Model{
protected $table = "film"; //Para nao dar o erro de singular e plural
protected $primaryKey = 'film_id';
public $timestamps = false;
use HasFactory;
protected $sql=['film_id', 'title', 'release_year'];
public function category(){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
}
}
Category model:
class category extends Model{
protected $table = "category";
protected $primaryKey = 'category_id';
public $timestamps = false;
use HasFactory;
protected $sql=['category_id','name'];
public function film(){
return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
}
}
NOTE: I realized that I need to add in the front of the Category model
->take(3)
But I don't know how to send the value(3 or other else) via $category query.
Upvotes: 0
Views: 106
Reputation: 46
You can simply put conditions in the closure of the "film" relationship on the controller to get 3 action movies or any number of movies.
Controller:
$limit = 3;
$category=category::with(['film'=>function($query)use($limit)
{
$query->limit($limt);
}])->where('name','=','Action')->first();
Upvotes: 1
Reputation: 125
Controller Side
$category=category::with('film')->where('name','=','Action')->film->category($value);
Model Side
public function category($value){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id')->where('foo', $value);
}
Upvotes: 0