【问题标题】:Laravel 5: Access database data from within modelLaravel 5:从模型内部访问数据库数据
【发布时间】:2017-03-27 00:09:03
【问题描述】:

我正在尝试使用 Laravel 访问数据库中的一些数据。我已经设置了我的模型,它工作正常,但是我试图通过在模型中创建一个方法来从另一个表中获取一些数据,该方法获取数据并将模型的属性设置为等于获取的数据。

为了获取数据,我尝试使用 $this->id 属性来获取该行的 ID 并使用它从另一个表中获取数据(例如:SomeOtherModel::where('other_id', '=', $this->id)->get();

但是,此时模型似乎没有从数据库中获取任何数据(例如:$this->id 为空)。我的构造函数如下所示:

public function __construct() {
    parent::__construct();
    $this->other_data = $this->getOtherData();
}

有没有办法从数据库中调用$this->id 属性,以便我可以在模型本身中使用它?

【问题讨论】:

  • 我建议使用Eloquent Relationships
  • 您可能正在尝试以某种方式使用Active Record Eloquent,这与其功能相冲突,而不是利用它。无论如何,在构造函数中显然还没有设置属性,所以你不能在那里这样做。阅读此xyproblem.info 并重新表述您的问题,也许我们可以为您提供帮助

标签: php eloquent laravel-5


【解决方案1】:

你的语法在我看来是错误的:

SomeOtherModel::where('other_id', '=', $this->id)->get();

你可以试试这个:

SomeOtherModel::where('other_id', $this->id)->get();

参考:https://laravel.com/docs/5.1/eloquent#retrieving-single-models

我希望这会有所帮助。

【讨论】:

  • 他的语法是正确的。您答案中的两行代码都是有效的,应该可以工作。
【解决方案2】:

解决方案解释here

class ExampleModel extends Model {
  protected $appends = ['otherdata'];

  public function getOtherdataAttribute() {
    return $this->getOtherData();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2015-07-30
    • 2013-12-06
    • 1970-01-01
    • 2016-05-16
    • 2019-02-25
    相关资源
    最近更新 更多