简体   繁体   中英

Laravel Eloquent many-to-many attach

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

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_id already exist just update it, other wise insert thr new one, but my problem is it always insters, it does not checks if the album_id already exsits

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?

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.

$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.

Contains method of 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.

Working code

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

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM