Using attach with a model extending a model

Posted 1 month ago by fdebieITV

I have these models, with the Image model extending the File model.

class Tag extends Model
{
    public function files()
    {
        return $this->belongsToMany('App\File', 'tag_file');
    }
}

class File extends Model
{
    public function tags()
    {
        return $this->belongsToMany('App\Tag', 'tag_file');
    }
}

class Image extends File
{
    // some specific functions for image operations
}

use Journal\Image;
class ImageController extends Controller
{
    public function something() {
        $image = new Image();
        $tag = App\Tag::firstOrCreate(['title' => 'some title']);
        $image->tags()->attach($tag);
        $image->save();
    }
}

When running the ImageController something function, a new record of File ( which was an Image ) is correctly added to the database files table. However, the tag is not added to the tag_file table; in stead, I get this error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'file_id' cannot be null (SQL: insert into `tag_file` (`tag_id`, `file_id`) values (1, ))

I assume this happens, because the $image->tags()->attach() uses image_id in stead of file_id, so file_id is left blank.

How can I make it work? Any ideas would be most welcome!

Please sign in or create an account to participate in this conversation.