Laravel Eloquent 多对多附加

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15564878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:37:51  来源:igfitidea点击:

Laravel Eloquent many-to-many attach

phpmysqllaravel

提问by Web Student

I am new to laravel, and trying to build a photo album with it. My problem is that i use the attach function to insert the user id and group id to my database, it works okay, but in the documentation it says this about the attach function

我是 laravel 的新手,并试图用它构建一个相册。我的问题是我使用附加功能将用户 ID 和组 ID 插入到我的数据库中,它工作正常,但在文档中它说明了附加功能

For example, perhaps the role you wish to attach to the user already exists. Just use the attach method:

例如,您希望附加到用户的角色可能已经存在。只需使用附加方法:

So i wanted to use it the same way, if the album_idalready exist just update it, other wise insert thr new one, but my problem is it always insters, it does not checks if the album_idalready exsits

所以我想以同样的方式使用它,如果album_id已经存在就更新它,否则插入新的,但我的问题是它总是插入,它不检查是否album_id已经存在

My model

我的模型

class User extends Eloquent 
{
    public static $timestamps = false;

    public function album()
    {
        return $this->has_many_and_belongs_to('album', 'users_album');
    }

}

Post function

发布功能

public function post_albums()
    {

      $user = User::find($this->id);

      $album_id = Input::get('album');

      $path = 'addons/uploads/albums/'.$this->id.'/'. $album_id . '/';

      $folders = array('path' => $path, 'small' => $path. 'small/', 'medium' => $path. 'medium/',  );

      if (! is_dir($path) ) 
      {
         foreach ($folders as $folder) 
         {
            @mkdir($folder, 0, true);
         }
      }


     $sizes = array( 
        array(50 , 50 , 'crop', $folders['small'], 90 ), 
        array(164 , 200 , 'crop', $folders['medium'], 90 ), 
     );

     $upload = Multup::open('photos', 'image|max:3000|mimes:jpg,gif,png',  $path)
             ->sizes( $sizes )
             ->upload();

     if($upload) 
     {
        $user->album()->attach($album_id);
        return Redirect::back();
     } 
     else 
     {
        // error show message remove folder
     }   

   }

Could please someone point out what im doing wrong? Or i totally misunderstod the attach function?

请有人指出我做错了什么吗?或者我完全误解了附加功能?

采纳答案by Web Student

Thanks @Collin i noticed i misunderstand i made my check yesterday

谢谢@Collin,我注意到我误解了我昨天进行了检查

$album = $user->album()->where_album_id($album_id)->get();

        if(empty($album))
        {
           $user->album()->attach($album_id);
        }

回答by Collin James

I believe you have misunderstood the attach function. The sync function uses attach to add relationships but only if the relationship doesn't already exist. Following what was done there, i'd suggest pulling a list of id's then only inserting if it doesn't already exist in the list.

我相信你误解了附加功能。同步函数使用 attach 来添加关系,但前提是关系不存在。按照那里所做的,我建议拉出一个 id 列表,然后只有在列表中不存在时才插入。

$current = $user->album()->lists( 'album_id' );
if ( !in_array( $album_id, $current ) )
{
    $user->album()->attach( $album_id );
}

On a side note I'm going to suggest that you follow the default naming convention from laravel. The relationship method should be $user->albums() because there are many of them. The pivot table should also be named 'album_user'. You will thank yourself later.

在旁注中,我将建议您遵循 laravel 的默认命名约定。关系方法应该是 $user->albums() 因为有很多。数据透视表也应命名为“album_user”。以后你会感谢自己。

回答by hhsadiq

Contains method of Laravel Collections

包含 Laravel Collections 的方法

The laravel collections provides a very useful method 'contains'. It determine if a key exists in the collection. You can get the collection in your case using $user->album. You can note the difference that album is without paranthesis.

laravel 集合提供了一个非常有用的方法“包含”。它确定集合中是否存在键。您可以使用$user->album. 您可以注意到专辑没有括号的区别。

Working code

工作代码

Now all you had to do is use the containsmethod. The full code will be.

现在您所要做的就是使用该contains方法。完整的代码将是。

if (!$user->album->contains($album_id)
{
   $user->album()->attach($album_id);
}

Its more cleaner and 'Laravel' way of getting the required solution.

获得所需解决方案的更清洁和“Laravel”方式。