【问题标题】:PHP, Laravel - Concatenation with String to ModelPHP,Laravel - 将字符串连接到模型
【发布时间】:2019-10-24 08:37:27
【问题描述】:

是否可以将字符串连接到模型?以下似乎不起作用。

我有Car ModelTrain Model。车辆将是CarTrain

$vehicle = 'Car';
$result = $vehicle::where('model', $value)->count() > 0;

以上代码存在如下错误。

Symfony\Component\Debug\Exception\FatalThrowableError: 在文件中找不到类“汽车”

如何连接?有可能吗?

【问题讨论】:

  • 是的,这是可能的。只需使用具有完整命名空间的模型,或者在命名空间声明后使用 use 添加命名空间。
  • 当您编写 Car::where 时,它​​会起作用吗?您将需要添加命名空间,因为当您添加任何模型时,它会在顶部的代码中导入......因为您添加了动态文件未命中。
  • 当我使用 Car::where 或 Train::where 时,它​​可以工作。

标签: php laravel class object


【解决方案1】:

我认为这是最接近您需要的, 你不必导入任何东西,因为你有一个动态值。 (如果您有 10 个可能的模型,则必须全部导入)

所以你应该这样做

$model = "Car";

$modelsPath = "\\App\\Models\\";

$className = $modelsPath.$model;

// if you need an instance you do this
// $instance = new $className;

$result = $className::where('model', $value)->count() > 0;

dd($result);

我通常做的是创建一个配置文件,其中包含所有可能性的数组,其中它们的关键是类型(在您的示例中为 Car、Bus、Train)

然后我使用作为输入(汽车)的键获取值,模型路径将在配置中!这样您以后就可以轻松地交换它并附加与该类型模型等相关的更多条件。

我希望这是有道理的

问候

【讨论】:

    【解决方案2】:
    use App\Car; //place this at the top of your page. Make sure the model exists
    

    【讨论】:

    • 不工作。存在以下错误。 Symfony\Component\Debug\Exception\FatalThrowableError: Class 'Car' not found
    【解决方案3】:

    是的,您可以根据条件连接模型。下面,我添加了一个可行的代码来实现。

    导入两个模型。

    //use App\Car;
    //use App\Train;
    
    $isCar = true; // boolean condition to check whether it is a car or train
    $classVariable = null;
    
    if ($variable) {
        $classVariable = new Car();
    }else{
        $classVariable = new Train();
    }
    
    $result = $classVariable->where('model', $value)->get();
    
    //this will provide you a car model query
    dd($result);
    

    更好的方法

    更好的方法是使用车辆模型和车辆类型。 在车辆表中添加一个 vehicle_type_id。

    所以当你需要检索汽车类型时,你可以使用

    //Suppose vehicle_type_id for car is 1
    $carVehicle = Vehicle::where('vehicle_type_id', 1)->get();
    //Suppose vehicle_type_id for train is 2
    $trainVehicle = Vehicle::where('vehicle_type_id', 2)->get();
    

    【讨论】:

      【解决方案4】:

      有可能

      use App\Car;
      use App\Train;
      
      /* Here You can now set Model name dynamically*/
      
      $vehicle = 'Car';
      $result = $vehicle::where('model', $value)->count() > 0;
      

      【讨论】:

        【解决方案5】:

        我认为一种方法可以如下:

        $vehicle = Car::class; //this will dynamically add full namespace of Car class. 
        $result = $vehicle::where('model', $value)->count() > 0;
        

        【讨论】:

          猜你喜欢
          • 2014-04-29
          • 2015-11-28
          • 1970-01-01
          • 2015-10-27
          • 1970-01-01
          • 2014-03-31
          • 2015-09-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多