framework icon indicating copy to clipboard operation
framework copied to clipboard

updated_at is ambiguous (belongsToMany delete() method call)

Open CoderFetch opened this issue 11 years ago • 5 comments

When attempting to call delete() on a belongsToMany relationship, I am getting this error in some cases:

Error code: SQLSTATE[23000]: Integrity constraint violation: 1052 Column '***updated_at***' in field list is ambiguous (SQL: update `users` inner join `forum_threads_read` on `users`.`id` = `forum_threads_read`.`user_id` set `users`.`deleted_at` = 2015-05-09 19:22:47, `updated_at` = 2015-05-09 19:22:47 where `users`.`deleted_at` is null and `forum_threads_read`.`topic_id` = 6)

I am using this relation code:

public function readers()
{
    return $this->belongsToMany('Fetch404\Core\Models\User', 'forum_threads_read', 'topic_id', 'user_id')->withTimestamps();
}

My migration:

Schema::create('forum_threads_read', function(Blueprint $table)
{
    $table->integer('topic_id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->timestamps();
});

The code I'm using to actually delete the relation data:

$category = $request->route()->getParameter('category');

$postIds = [];

foreach($category->channels as $channel)
{
     foreach($channel->topics as $topic)
      {
           foreach($topic->posts as $post) $postIds[] = $post->id;

           $topic->readers()->delete();
           $topic->posts()->delete();
           $topic->delete();
      }

      $channel->delete();
}

Now, there is one weird thing about this: Creating a function called, say, "deleteReaders", with the following code:

public function deleteReaders()
{
    return DB::table('forum_threads_read')
        ->where('topic_id', '=', $this->id)
        ->delete();
}

The code above works perfectly fine. So it works with the query builder, but not Eloquent itself, which is weird. I have seen others have this issue, and I am wondering what I should do (I can't get rid of the timestamps, because they are crucial for the unread/read system.)

CoderFetch avatar May 09 '15 19:05 CoderFetch

@fetch404 can you post both models and migrations so i can reproduce it?

hernandev avatar May 12 '15 01:05 hernandev

Okay. The Topic class:

<?php namespace Fetch404\Core\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

use Auth;
use Illuminate\Support\Facades\DB;
use URL;

use Zizaco\Entrust\EntrustFacade as Entrust;

class Topic extends Model {

    //
    protected $table = 'topics';
    protected $fillable = ['title', 'user_id', 'channel_id', 'locked', 'pinned', 'slug'];

    // Thread constants
    const     STATUS_UNREAD  = 'unread';

    public function channel()
    {
        return $this->belongsTo('Fetch404\Core\Models\Channel');
    }

    public function user()
    {
        return $this->belongsTo('Fetch404\Core\Models\User', 'user_id');
    }

    public function posts()
    {
        return $this->hasMany('Fetch404\Core\Models\Post');
    }

    public function isLocked()
    {
        return $this->locked == 1;
    }

    public function isPinned()
    {
        return $this->pinned == 1;
    }

    public function getLatestPost()
    {
        $posts = $this->posts()->orderBy('created_at', 'desc');

        return $posts->first();
    }

    public function getPostsPaginatedAttribute()
    {
        return $this->posts()->paginate(config('forumsettings.threads.postsPerPage', 5));
    }

    public function getLastPageAttribute()
    {
        return $this->postsPaginated->lastPage();
    }   

    public function getPageLinksAttribute()
    {
        return $this->postsPaginated->render();
    }

    public function getRouteAttribute()
    {
        return route('forum.get.show.thread', [$this->channel->id, $this->id]);
    }

    public function getShowReplyRouteAttribute()
    {
        return route('forum.get.show.thread.reply', [$this->channel->id, $this->id]);
    }

    public function getReplyRouteAttribute()
    {
        return route('forum.post.thread.reply', [$this->channel->id, $this->id]);
    }

    public function getQuickReplyRouteAttribute()
    {
        return route('forum.post.quick-reply.thread', [$this->channel->id, $this->id]);
    }

    public function getCanViewAttribute()
    {
        return ($this->channel->canView(Auth::user()) && $this->channel->category->canView(Auth::user()));
    }

    public function getReplyCountAttribute()
    {
        $replyCount = $this->posts()->count() - 1;

        return $replyCount < 0 ? 0 : $replyCount;
    }

    public function getCanReplyAttribute()
    {
        if (Entrust::can('replyToAllThreads')) return true;

        if (Auth::check() && Auth::user()->isConfirmed() && $this->locked == 0 && $this->channel->can(6, Auth::user())) return true;

        return false;
    }

    public function getUser()
    {
        return $this->user;
    }

    public function getOldAttribute()
    {
        $now = Carbon::now();
        $now->subMonths(1);

        // The thread is old if there have been no posts since a month ago.

        return $this->updated_at->toDateTimeString() < $now->toDateTimeString();
    }

    public function readers()
    {
        return $this->belongsToMany('Fetch404\Core\Models\User', 'forum_threads_read', 'topic_id', 'user_id')->withTimestamps();
    }

    // Current user: reader attributes
    public function getReaderAttribute()
    {
        if (!is_null(Auth::user()))
        {
            $reader = $this->readers()->where('user_id', '=', Auth::id())->first();
            return (!is_null($reader)) ? $reader->pivot : null;
        }

        return null;
    }

    public function getUserReadStatusAttribute()
    {
        if (!$this->old && !is_null(Auth::user()))
        {
            if (is_null($this->reader))
            {
                return self::STATUS_UNREAD;
            }

            return ($this->updatedSince($this->reader)) ? self::STATUS_UNREAD : false;
        }

        return false;
    }

    public function updatedSince(&$model)
    {
        return ($this->updated_at > $model->updated_at);
    }

    public function markAsRead($userID)
    {
        if (is_null($this->reader))
        {
            $this->readers()->attach($userID);
        }
        elseif ($this->updatedSince($this->reader))
        {
            $this->reader->touch();
        }
    }

    public function deleteReaders()
    {
        return DB::table('forum_threads_read')
            ->where('topic_id', '=', $this->id)
            ->delete();
    }
}

And the User class doesn't have any relationship to the read topics, but here it is anyway:

<?php namespace Fetch404\Core\Models;

use Fetch404\Core\Utilities\PageableCollection;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

use Zizaco\Entrust\Traits\EntrustUserTrait;
use Cmgmyr\Messenger\Traits\Messagable;

use Illuminate\Database\Eloquent\SoftDeletes;

use Auth;
use URL;

use Fetch404\Core\Traits\HasProfilePosts;
use Fetch404\Core\Traits\BaseUser;
use Fetch404\Core\Traits\FollowableTrait as Followable;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract 
{
    use Authenticatable, CanResetPassword, EntrustUserTrait, Messagable, SoftDeletes, BaseUser, Followable, HasProfilePosts;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'slug', 'confirmed', 'is_banned', 'banned_until', 'last_active_desc', 'last_active', 'is_online'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    protected $dates = ['deleted_at', 'last_active', 'banned_until'];

}

The real stuff is in BaseUser, though.

<?php namespace Fetch404\Core\Traits;

use Carbon\Carbon;
use Cmgmyr\Messenger\Models\Thread;

use Auth;

use Fetch404\Core\Models\AccountConfirmation;
use Fetch404\Core\Models\User;
use Illuminate\Support\Facades\Storage;

trait BaseUser {

    /**
     * Relationship functions
     * DO NOT MODIFY
     */

    /**
     * Get all the topics created by a user.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function topics()
    {
        return $this->hasMany('Fetch404\Core\Models\Topic');
    }

    /**
    * Get all the posts created by a user.
    *
    * @return \Illuminate\Database\Eloquent\Relations\HasMany
    */
    public function posts()
    {
        return $this->hasMany('Fetch404\Core\Models\Post');
    }

    /**
     * Get all of the user's news posts.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function news()
    {
        return $this->hasMany('Fetch404\Core\Models\News');
    }

    /**
     * Get any name changes the user has had.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function nameChanges()
    {
        return $this->hasMany('Fetch404\Core\Models\NameChange');
    }

    /**
     * Get any likes that the user gave.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function likesGiven()
    {
        return $this->hasMany('Fetch404\Core\Models\Like', 'user_id');
    }

    /**
     * Get any likes that the user received.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function likesReceived()
    {
        return $this->hasMany('Fetch404\Core\Models\Like', 'liked_user_id');
    }

    /**
     * Get a user's settings.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function settings()
    {
        return $this->hasMany('Fetch404\Core\Models\UserSetting');
    }

    /**
     * Get the value of a certain setting for this user.
     * If it has not yet been set, a default value will be returned,
     * or if none is specified, null.
     *
     * @param $name
     * @param $default
     * @return string
     */
    public function getSetting($name, $default = null)
    {
        $setting = $this->settings()->where('name', '=', $name)->first();

        if ($setting == null)
        {
            return ($default == null ? null : $default);
        }
        else
        {
            return $setting->value;
        }
    }

    /**
     * Set a specific setting for this user.
     * If it has not yet been set, it will be created with the given value.
     *
     * @param $name
     * @param $value
     * @return void
     */
    public function setSetting($name, $value)
    {
        $setting = $this->settings()->where('name', '=', $name)->first();

        if ($setting == null)
        {
            return $this->settings()->create(array(
                'name' => $name,
                'value' => $value,
                'user_id' => $this->getId()
            ));
        }
        else
        {
            return $setting->update(array(
                'value' => $value
            ));
        }

        return false;
    }

    /**
     * Get all of the user's recent notifications.
     *
     * @return mixed
     */
    public function notifications()
    {
        return $this->hasMany('Fetch404\Core\Models\Notification')
            ->with(['user', 'subject'])
            ->take(5)
            ->latest();
    }

    /**
     * Get all of the user's unread notifications.
     *
     * @return mixed
     */
    public function unreadNotifications()
    {
        return $this->notifications()->unread($this->id);
    }

    /**
     * Get the user's account confirmation object.
     *
     * @return AccountConfirmation
     */
    public function getAccountConfirmation()
    {
        $confirmation = AccountConfirmation::where(
            'user_id',
            '=',
            $this->id
        )->first();

        if ($confirmation == null)
        {
            return null;
        }

        if ($this->isConfirmed())
        {
            return null;
        }

        return $confirmation;
    }

    /**
     * Get a user's conversations.
     *
     * @return Thread
     */
    public function getConversations()
    {
        return Thread::forUser($this->id);
    }

    /**
     * Attribute functions
     *
     */
    /**
     * Is the user confirmed?
     *
     * @return boolean
     */
    public function isConfirmed()
    {
        return $this->confirmed == 1;
    }

    /**
     * Get the user's profile URL.
     *
     * @return string
     */
    public function getProfileURLAttribute()
    {
        return route('profile.get.show', ['slug' => $this->slug, 'id' => $this->id]);
    }

    /**
     * Get the user's name color.
     *
     * @return string
     */
    public function getRoleColorAttribute()
    {
        if ($this->hasRole('owner'))
        {
            return "#CC0000";
        }
        elseif ($this->hasRole('admin'))
        {
            return "#ccc";
        }
        else
        {
            return "#fff";
        }
    }

    /**
     * Get a user's prefix.
     *
     * @return string
     */
    public function getPrefixAttribute()
    {
        if ($this->roles->count() > 0)
        {
            $prefix = '[' . $this->roles()->orderBy('created_at', 'desc')->first()->display_name . ']';
            return $prefix;
        }
        else
        {
            return "[Member]";
        }
    }

    /**
     * Get the generated URL to a user's avatar.
     * Returns a link to the default avatar if the user does not have an avatar
     *
     * @param boolean $large
     * @return string
     */
    public function getAvatarURL($large = true)
    {
        $extensions = [
            'png',
            'jpg'
        ];

        foreach($extensions as $ext)
        {
            if (Storage::exists('avatars/' . $this->id . '.' . $ext))
            {
                return 'avatars/' . $this->id . '.' . $ext;
            }
        }

        return '/assets/img/defaultavatar' . ($large ? 'large' : '') . '.png';
    }
    /**
     * Other functions (role IDs, etc)
     *
     * Don't modify these!
     */

    /**
     * Returns user's current role ids only.
     * @return array|bool
     */
    public function currentRoleIds()
    {
        $roles = $this->roles;
        $roleIds = false;
        if( !empty( $roles ) ) {
            $roleIds = array();
            foreach( $roles as $role )
            {
                $roleIds[] = $role->id;
            }
        }
        return $roleIds;
    }

    /**
     * Save a user's roles, input is taken from the Select2 inputs.
     *
     * @param array $inputRoles
     * @return void
     */
    public function saveRoles($inputRoles)
    {
        if(! empty($inputRoles)) {
            $this->roles()->sync($inputRoles);
        } else {
            $this->roles()->detach();
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function getJoinedOn()
    {
        $now = Carbon::now();
        $now->subDays(7);

        return ($this->created_at > $now->toDateTimeString() ? $this->created_at->diffForHumans() : $this->created_at->format('M jS, Y'));
    }

    public function getLastActivity()
    {
        $now = Carbon::now();
        $now->subDays(7);

        if ($this->last_active == null)
        {
            return ($this->created_at == null ? "never" : ($this->created_at > $now->toDateTimeString() ? $this->created_at->diffForHumans() : $this->created_at->format('M jS, Y')));
        }

        if (!Auth::check() && $this->getSetting("show_when_im_online", 1) == '0') return "[hidden]";

        if ($this->getSetting("show_when_im_online", 1) == '0' && Auth::id() != $this->id)
        {
            return "[hidden]";
        }

        return ($this->last_active > $now->toDateTimeString() ? $this->last_active->diffForHumans() : $this->last_active->format('M jS, Y'));
    }

    public function getLastActiveDesc()
    {
        if (!Auth::check() && $this->getSetting("show_when_im_online", 1) == '0') return "[hidden]";

        if ($this->getSetting("show_when_im_online", 1) == '0' && Auth::id() != $this->id)
        {
            return "[hidden]";
        }

        return $this->last_active_desc;
    }

    public function postCount()
    {
        return $this->posts()->count();
    }

    /**
     * Check to see if the current user is banned.
     *
     * @return bool
     */
    public function isBanned()
    {
        if ($this->banned_until != null)
        {
            return ($this->is_banned == 1 && $this->banned_until > Carbon::now()->toDateTimeString());
        }

        return $this->is_banned == 1;
    }

    /**
     * Check to see if the current user "is" a certain user
     * The only parameter type accepted is a User object.
     *
     * @param User $user
     * @return boolean
     */
    public function isUser(User $user)
    {
        if (is_null($user)) return false;

        return $this->getId() == $user->getId();
    }

    /**
     * Get a user's current "status" (their latest profile post)
     *
     * @return object
     */
    public function currentStatus()
    {
        $profilePost = $this->profilePosts()
            ->where('from_user_id', '=', $this->getId())
            ->where('to_user_id', '=', $this->getId())
            ->first();

        return $profilePost;
    }

    /**
     * Query scopes
     *
     * @param $query
     * @return mixed
     */
    public function scopeBanned($query)
    {
        return $query->where('is_banned', '=', 1);
    }
}

CoderFetch avatar May 12 '15 10:05 CoderFetch

That's way too much code for us to deal with.

GrahamCampbell avatar May 31 '15 18:05 GrahamCampbell

@GrahamCampbell Okay, I think I know how to fix it anyway.

CoderFetch avatar May 31 '15 21:05 CoderFetch

Can you share your fix please?

zlatevbg avatar May 18 '18 11:05 zlatevbg