简体   繁体   English

将数据从表复制到另一个表并应用一对多关系

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

This is my Report Model 这是我的报告模型

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

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

This is my Site Model 这是我的网站模型

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

This is my ReportController 这是我的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);
}

My Controller is not yet working as well. 我的控制器还无法正常工作。 The thing is I would like to copy all the three files from sites table to reports table. 事情是我想将所有三个文件从站点表复制到报告表。

Is it possible in insertInto ? insertInto可能吗?

My code on ReportController shows you that I'm selecting data from reports table but I am the one who puts data to reports table to see the output but it is not yet working because of the it cant reach out the value of site_name even though I already put a relationship between the two tables. 我在ReportController上的代码向您展示了我正在从报告表中选择数据,但是我是将数据放入报告表中以查看输出的人,但由于它无法伸出site_name的值,因此它仍无法正常工作,即使我已经在两个表之间建立了关系。

You're not actually using Eloquent in your controller you're just using the Query Builder ( DB ). 您实际上并没有在控制器中使用Eloquent,而只是在使用查询生成器( DB )。 This will mean that you don't have access to anything from your Eloquent models. 这意味着您无权访问Eloquent模型中的任何内容。

Try: 尝试:

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

I've added id to the list of columns as I'm pretty sure you'll need that to use whereHas . 我已经将id添加到列列表中,因为我很确定您需要使用whereHas

NB to use a variable from the parent scope inside a closure you need to pass it in using use() . 注意要在闭包内部使用来自父作用域的变量,您需要使用use()传递它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM