如何从laravel中的自定义方法获取当前模型

Jas*_*ick 6 php models laravel eloquent laravel-5

我不确定我是否正确地提出问题,但这正是我想要做的.

所以我们可以从中得到电流

$model = Model::find($id)

然后我们可以得到它的关系,如:

$model->relationships()->id

然后我们有这样的行动:

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

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

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

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

   public function customMethod($params){
         //Do something with relationship id
   }
Run Code Online (Sandbox Code Playgroud)

但更进一步,customMethod我将如何获得$models像id这样的信息?

对不起,如果这可能有点令人困惑.

jed*_*ylo 2

首先,如果要访问相关对象,可以通过访问与关系同名的属性来实现。在您的情况下,为了从关联访问对象您需要通过以下方式执行此操作:

$model->relationships //returns related object or collection of objects
Run Code Online (Sandbox Code Playgroud)

代替

$model->relationships() //returns relation definition
Run Code Online (Sandbox Code Playgroud)

其次,如果你想访问相关对象的属性,你可以用同样的方式来做:

$relatedObjectName = $model->relationship->name; // this works if you have a single object on the other end of relations
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关如何定义和使用关系的更多信息:http://laravel.com/docs/5.1/eloquent-relationships