0

I have two tables, news and news_links. The news table looks like this (id, title, body, date_published) and the news_links look like this (id, news_id, url).

I'm trying to build a query where I can insert a news array:

array( 
  array(
    "id" => "123456",
    "title" => "First Title",
    "body" => "First body text",
    "date_published" => "01-01-16"
  )
  array(
    "id" => "22222",
    "title" => "Second Title",
    "body" => "Second body text",
    "date_published" => "01-01-16"
  )
)

This array will contain multiple array, this is just an example.

Links related to these news will also be inserted.

array(
  array(
    "0" => "1",
    "1" => "123456",
    "2" => "img_url"
  )
  array(
    "0" => "2",
    "1" => "123456",
    "2" => "img_url"
  )
  array(
    "0" => "2",
    "1" => "22222",
    "2" => "img_url"
  )
)

Will I have to build a foreach loop and run multiple queries or is there a way to run a single query and insert everything into both news and news_links?

2 Answers 2

1

No, you can't use one query to insert data in two different tables. However, you can combine several inserts for one table in one query. It will look like

INSERT INTO news_links VALUES(1,123456,'url'),(2,123456,'url'),(2,22222,'url');
Sign up to request clarification or add additional context in comments.

3 Comments

So I'll have to do some kind of implode() on my array to build the query I take it?
In Laravel you can simply do it like \DB::table('table name')->insert([['id' => 1, 'news_id' => 123456, 'url' => 'url'], [], []]) @JesperAndersen
I'll probalby have to use DB::insert() since I'm using "insert ignore into 'table'", but it's good to know I can use Query Builder like that. Thank you!
0

I think this is a simple solution NewsLink::insert(array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.