簡體   English   中英

將數據從表復制到另一個表並應用一對多關系

[英]Copying Data from table to another table and applying one to many relationship

這是我的報告模型

protected $fillable = [
    'site_url',
    'reciepients',
    'monthly_email_date'
];

public function site()
{
    return $this->belongsTo('App\Site');
}

這是我的網站模型

public function report()
{
    return $this->hasMany('App\Report');
}

這是我的ReportController

public function showSpecificSite($site_name)
{

$records = DB::table('reports')
          ->select('email_date','url','recipient') 
          ->whereHas('sites', function($query){
                    $query->where('site_name',$site_name);
           })
          ->get();

  return view('newsite')->with('records',$records)
  ->with('site_name',$site_name);
}

我的控制器還無法正常工作。 事情是我想將所有三個文件從站點表復制到報告表。

insertInto可能嗎?

我在ReportController上的代碼向您展示了我正在從報告表中選擇數據,但是我是將數據放入報告表中以查看輸出的人,但由於它無法伸出site_name的值,因此它仍無法正常工作,即使我已經在兩個表之間建立了關系。

您實際上並沒有在控制器中使用Eloquent,而只是在使用查詢生成器( DB )。 這意味着您無權訪問Eloquent模型中的任何內容。

嘗試:

$records = \App\Report::whereHas('site', function($query) use($site_name) {
        $query->where('site_name', $site_name);
    })->get(['id', 'email_date', 'url', 'recipient']);

我已經將id添加到列列表中,因為我很確定您需要使用whereHas

注意要在閉包內部使用來自父作用域的變量,您需要使用use()傳遞它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM