Skip to main content

How to make shortest code?

I use the following code to insert multi array to database:

foreach($request->category as $k => $v){
                $category[] = array(
                    "category_id" => $v,
                    "announcement_id" => $announcement->id
                );
            }

            AnnouncementCategory::insert($category);

So, input data is POST array $request->category. I need to refactoring this code

I tried this code:

$announcement->categories()->attach($request->category);

In model Announcement I have:

 public function categories()
    {
        return $this->hasMany("App\AnnouncementCategory", "announcement_id", "id");
    }

Solved

If you define in your Announcement model relationship like this:

public function categories() 
{
   return $this->belongsToMany(AnnouncementCategory::class);
}

you can do it like this:

$announcement->categories()->attach($request->category);

EDIT

I see you updated your question and added categories relationship. But looking at your code, AnnounceCategory is rather pivot table, so you should use belongsToMany as I showed instead of hasMany


You can do it in one line if the request matches the columns:

AnnouncementCategory::insert($request->all());

Then in your AnnouncementCategory model, make sure you declare the protected $fillable array where you specify which field could be populated.


Comments

Popular posts from this blog

removing zeros from the right and adding some to the left of a number?

Suppose I have the following vector test First I want to get the remove the zeros, to obtain something like: test2 Then, I want to add zeros to the left in order to have 6 digits. That part I know how to do: test3 Can you help me with the first step? Solved You can use regular expressions: as.integer(sub("0*$", "", test)) # [1] 3745 22704 Also, here is a fun one using recursion: remove_zeroes Benchmarks: test Late to the party but here's a qdap approach: test

Ruby on Rails as_json limit

I have this "as_json" method in my Post model: def as_json(options={}) super(options.merge(:include => { :comments => { :include => [:user] }, :hashtags => {}, :user => {}, :group => {} })) end I'd like to set a limit attribute in :comments like this: def as_json(options={}) super(options.merge(:include => { :comments => { :include => [:user], :limit => 10 }, :hashtags => {}, :user => {}, :group => {} })) end but it doesn't work. How should I proceed? Solved I think that you have only one possibility. I suppouse that you have a has_many :comments association in your Post model So you can define the next has_many association in your Post model, something like this: has_many :ten_comments, -> { limit(10) }, class_name: "Comment", foreign_key: :post_id And then you will be able to do this in the as_json method: def as_json(options={}) super(options.merge(:include => { :te...