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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?