[英]Laravel: How to send value from Controller to Model?
如何從 Controller 發送一個值到 Model 以及如何接收 Model 中的值。
我在上面放了一張我的數據庫表的圖片。
示例:如果我輸入3 部動作片
$category=category::with('film')->where('name','=','Action')->first();
電影 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');
}
}
類別 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');
}
}
注意:我意識到我需要在類別 model 的前面添加
->拿(3)
但我不知道如何通過 $category 查詢發送值(3 或其他)。
您可以簡單地在關閉 controller 上的“電影”關系中設置條件,以獲得 3 部動作片或任意數量的電影。
Controller:
$limit = 3;
$category=category::with(['film'=>function($query)use($limit)
{
$query->limit($limt);
}])->where('name','=','Action')->first();
Controller 方
$category=category::with('film')->where('name','=','Action')->film->category($value);
Model 側
public function category($value){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id')->where('foo', $value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.