【问题标题】:How to call a model function from another model in laravel如何从 laravel 中的另一个模型调用模型函数
【发布时间】:2018-02-08 10:37:45
【问题描述】:

我想在另一个名为“property”的模型中调用listcity函数

/model/Crawler.php

class Crawler extends Model {
public function listcity($statename)
  {

    $ins="exec Prc_Lst_CityMaster @CountryName = 'India', @StateName = '".$statename."'";

      return DB::select($ins);
  }
}

/model/Property.php

use App\Models\Crawler,
class Property extends Model {
 public function __construct(Crawler $Crawler)
    {     
        $this->Crawler = $Crawler;

    }
 public function propertyDetails($id)
    {
$this->Crawler->listcity($id);
}
}

但我得到一个错误

错误异常 (E_NOTICE) 试图获取非对象的属性

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您应该使用关系而不是将模型注入另一个模型。但是如果你想这样做,你需要手动而不是通过构造函数:

    public function propertyDetails($id)
    {
        app('App\Crawler')->listcity($id);
    }
    

    【讨论】:

      【解决方案2】:

      您需要在模型中为Crawler 添加一个属性。

      public $Crawler;
      
      public function __construct(Crawler $Crawler)
      {     
            $this->Crawler = $Crawler;
      }
      

      【讨论】:

      • 如果我们使用此代码,我们会收到以下错误消息 SQLSTATE[HY090]: [Microsoft][ODBC Driver Manager] Invalid string or buffer length (SQL: )
      猜你喜欢
      • 2014-01-20
      • 1970-01-01
      • 2020-08-02
      • 2014-11-18
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      • 2015-06-10
      相关资源
      最近更新 更多