Php Laravel将变量从控制器传递给模型

时间:2018-05-01 12:10:24

标签: php laravel model

我对laravel很新,我真的在这里挣扎。

所以我想要的是,将{wildcard}传递给模型中的数据库查询

我的代码

模型

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;


class Product extends Model
{
    protected $table = "product";
    public $timestamps = false;

    public function scopeSingleProduct($id){
        $products = DB::select("SELECT * FROM product WHERE id = '$id'");

        return  $products;
    }

}

控制器

public function show($id){
      $product = Product::SingleProduct($id);

      return view('products.product',compact("product"));
} 

查看

{{ $product }}

因此,如果我将 $ id 设置为模型文件中的静态数字,我的代码基本上可以正常工作,例如1,2,3,4等等,但这里似乎没有正常工作,有人能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:0)

尝试这个

<强>模型

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;


class Product extends Model
{
    protected $table = "product";
    public $timestamps = false;
    //create relationships, that's it, no need to write queries

}

<强>控制器

public function show(Request $request){
      //$request->id is the product id, you can pass it through query string or by post
      if($request->id>0){
        $product = Product::where('id', $request->id)->first();

        return view('products.product',compact("product"));
      }
} 

查看

{{ $product }}