Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent many-to-many attach

Tags:

php

mysql

laravel

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?

like image 225
Web Student Avatar asked Mar 22 '13 07:03

Web Student


People also ask

How do you attach a many to many relationship?

The key in many to many relationship is the join (or pivot) table. The pivot table allows the relationship id from one model to be related to many other models and vice-versa. Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany.

How do you do a many to many relationship in Laravel?

each table is connected with each other. now we will create many to many relationships with each other by using the laravel Eloquent Model. We will first create database migration, then model, retrieve records and then how to create records too. So you can also see database table structure on below screen.

What is difference between attach and sync in Laravel?

The attach function only adds records to the Pivot table. The sync function replaces the current records with the new records. This is very useful for updating a model.

What is BelongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.


1 Answers

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.

like image 175
Collin James Avatar answered Sep 19 '22 12:09

Collin James