我如何从laravel自定义方法获得当前模型


How do I get the current model from custom method in laravel

我不确定我问的问题是否正确,但这就是我想做的。

所以我们可以从 得到电流

$model = Model::find($id)

那么我们可以得到它的关系如下:

$model->relationships()->id

然后我们有这样的动作:

$model->relationships()->detach(4);

我的问题是,我们可以有一个自定义方法,如:

$model->relationships()->customMethod($params); ?

,在模型中它可能看起来像:

   public function customMethod($params){
         //Do something with relationship id
   }

但更重要的是,我如何在customMethod中获得$models信息,如id?

首先,如果您想访问一个相关的对象,您可以通过访问一个与关系同名的属性来实现。在您的示例中,为了从关系访问对象,您需要这样做:

$model->relationships //returns related object or collection of objects

代替

$model->relationships() //returns relation definition

其次,如果你想访问相关对象的属性,你可以这样做:

$relatedObjectName = $model->relationship->name; // this works if you have a single object on the other end of relations

最后,如果你想调用一个相关模型上的方法,你需要在相关的模型类中实现这个方法。

class A extends Eloquent {
  public function b() {
    return $this->belongsTo('Some'Namespace'B');
  }
  public function cs() {
    return $this->hasMany('Some'Namespace'C');
  }
}
class B extends Eloquent {
  public function printId() {
    echo $this->id;
  }
}
class C extends Eloquent {
  public function printId() {
    echo $this->id;
  }
}
$a = A::find(5);
$a->b->printId(); //call method on related object
foreach ($a->cs as $c) { //iterate the collection
  $c->printId(); //call method on related object
}

你可以阅读更多关于如何定义和使用关系在这里:http://laravel.com/docs/5.1/eloquent-relationships