doudi2833 2018-08-16 17:19
浏览 46
已采纳

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

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

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 ?

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.

  • 写回答

1条回答 默认 最新

  • dousu1900 2018-08-16 17:54
    关注

    You're not actually using Eloquent in your controller you're just using the Query Builder (DB). This will mean that you don't have access to anything from your Eloquent models.

    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.

    NB to use a variable from the parent scope inside a closure you need to pass it in using use().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试