katie hudson
katie hudson

Reputation: 2893

Saving Model data to database

I have a Report Model which is like the following.

class Report extends Model
{
    protected $table = 'reports';
    protected $guarded = [];

    public function leadsCollection()
    {
        return $this->hasMany('App\ReportModels\LeadsCollection');
    }
}

A Report can have many LeadsCollection, its Model is the following.

class LeadsCollection extends Model
{
    protected $table = 'leadsCollection';
    protected $guarded = [];
    private $xmlElement;

    public function __construct($xmlElement = null, $attributes = array())  {
        parent::__construct($attributes);
        $this->xmlElement = $xmlElement;
    }

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

    function asArray(){
        $reportItem = array();

        foreach($this->xmlElement->Leads->Lead as $lead) {
            $dateIdentified = date("d/m/Y", strtotime($lead->Date));

            $reportItem[] = array(
                'LeadID' => (string)$lead->ID,
                'Client' => (string)$lead->Client->Name,
                'Category' => (string)$lead->Category,
                'DateIdentified' => $dateIdentified,
                'LeadName' => (string)$lead->Name,
                'Owner' => (string)$lead->Owner->Name
            );
        }

        return $reportItem;
    }
}

Now I am trying to save some data to a database. So I get a list of all Leads by calling my LeadsCollection and passing it an XML list of Leads. I then loop these Leads and add it to an array. At the same time however I need to save it to the database. This is what I have so far.

public function getForecastReportForLeads() {
    $leads = new LeadsCollection(new \SimpleXMLElement(Helper::getCurrentLeads()));

    $reportArray = array();

    foreach ($leads->asArray() as $lead) {
        $report = new Report();
        $report->reportName = 'Lead Forecast';
        if($report->save()) {
            $leads->leadId = $lead['LeadID'];
            $leads->leadCategory = $lead['Category'];
            $leads->dateIdentified = $lead['DateIdentified'];
            $leads->leadName = $lead['LeadName'];
            $leads->owner = $lead['Owner'];
            $leads->client = $lead['Client'];
            $leads->report_id = $report->id;
            $leads->save();

            $reportItem = array(
                'leadData' => $lead
            );

            $reportArray[] = $reportItem;
        }
    }

    return $reportArray;
}

So I create the Report item, and within the database if I have 7 Leads I end up with 7 Report rows within my reports table, as it should be. However, when I save the Leads, I only end up with 1 row in my leadsCollection table, every other entry seems to be overridden. I think this is because I am not creating the Lead Object within the loop. However, I cant really create it within the loop because I need to loop whats returned when I first create it.

Not sure how clear I am but is there anything I can add to my Model so I can stop any overriding? Or do I need to do this another way?

Thanks

Upvotes: 1

Views: 98

Answers (1)

Cristo
Cristo

Reputation: 710

Either you get the variable inside the save method or initialize the new

$report = new Report($reportItem);

$report->save($report)

I'm having a similar Issue right, let me show my code. It would work for your case. My bug is that I'm updating and the plan_detail.id gets moved instead of creating a new one. But if you create would be fine:

public function store(Request $request)
{
    $this->validate($request, [ 'title' => 'required',
                                'description' => 'required']);
    $input = $request->all();

    $plan_details = Plan_Detail::ofUser()->get();
    $plan = new Plan($request->all());

    DB::beginTransaction();
    Auth::user()->plans()->save($plan);

    try {
      foreach ($plan_details as $k => $plan_detail)
        Plan::find($plan['id'])->details()->save($plan_detail);
      DB::commit();
    } catch (Exception $e) {
      Log::error("PGSQL plan detail " . $e->message());
      DB::rollback();
      session()->flash('message', 'Error al guardar el plan de entreno');
    }

    return redirect('plans');
}

Upvotes: 1

Related Questions