如何通过名称获取模型的关系?

时间:2018-07-11 16:33:47

标签: php laravel

有没有一种方法可以通过它的名字来调用关系?

代替此:

enter code here
Try this:

$vacations = array();
foreach($data['vacations'] as $key => $value){
   foreach($value as $index => $person){
      $vacations[$person['drivernumber']] = array();
      $vacations[$person['drivernumber']]['name'] = $person['name'];
      $vacations[$person['drivernumber']]['drivenumber'] = $person['drivenumber'];
      $vacations[$person['drivernumber']]['vacations'] = "";
   }
}// With this, you will have the array $vacations with the drivernumbers as keys without duplicates and initialized the name, drivenumber and vacations string.

foreach($data['vacations'] as $key => $value){
   foreach($value as $index => $person){
       $vacations[$person[drivenumber]]['vacations'] += $person['period_start'] . "-" . $person['period_end'] . " ";
   }
}//This will concatenate all the period_start and period_end of each person in their respective position in the array.

foreach($vacations as $key => $value){
    echo $value['name'] . " " . $value['drivernumber'] . " " . $value['vacations'];
}//Finally.. print in the format that you are requesting.

我想使用这样的东西:

$user->comments()->create([]);

我已经尝试过了,但是我得到了:

$relation = 'comments';
$user->getRelation($relation)->create([]);

3 个答案:

答案 0 :(得分:1)

我认为您必须更加具体。但是,如果您想获得口才好的关系的结果,您可以:

$books = App\Book::with('author')->get();

作者在哪里,是一种关系。

来源:https://laravel.com/docs/5.6/eloquent-relationships

答案 1 :(得分:0)

您是要提供动态关系名称吗?如果是这样,您可以这样做:

$relation = 'comments';

$user->$relation->create([]);

答案 2 :(得分:0)

您需要考虑两种情况。

1)创建用户并且未附加评论时,getRelation($string)返回Error: undefine index RELATION NAME 2)当用户有评论并通过getRelation($string)查找关系时,它就像是一种魅力。

该问题的解决方法是您需要首先加载该关系。让我给你举个例子。

$user = new User();
$relation = 'comments';
//load method is used to load a relation.
$user->load($relation)->create(['field_name'=>"SOME VALUE"]);

尝试一下,让我知道它是否有效。