Laravel /ORM Doesnt create related table - php

How can I add value to a ORM related variable?
It contains a news and comments Model, as shown below:
class News extends Model {
protected $connection = 'mysql';
protected $primaryKey = 'id';
protected $table = 'news';
protected $fillable = array(
'id',
'name',
'category',
'type',
'datetime',
'shortdesc',
'desciption'
);
public $timestamps = false;
public function comments()
{
return $this->hasMany('App\Comments');
}
Comments table
class Comments extends Model {
protected $connection = 'mysql';
protected $primaryKey = 'id';
protected $table = 'comments';
protected $fillable = array(
'id',
'news_id',
'name',
'description'
);
public $timestamps = false;
public function news()
{
return $this->belongsTo('App\News','news_id');
}};
And when I try to add this values it creates only News table
without related Comments table.(Doesn't throw any exception, just creates News table)
public function AddData()
{
$row=new News;
$row->name="Myname";
$row->category="vcc";
$row->type="2";
$row->comments()->news_id="1";
$row->comments()->name="someval";
$row->save();
return view::make('first_view');
}

There is a problem when you are inserting your related Comment model. There are many ways to solve your problem.
Solution I prefer to use:
public function AddData()
{
// Create news model
$news = News::create([
'name' => 'Some name',
'category' => 'somecategory',
....
]);
// Create comment through news model
// news_id will automatically be inserted
$comment = $news->comments()->create([
'name' => 'some name'
]);
}
See documentation

Related

CodeIgniter 4 : no error but data won't insert to database

No error while I try to insert the data. in fact the session indicator shows that I successfully inserted the data, but when I check the database it was nothing.
public function save_agenda()
{
$idkelas = $this->request->getVar('id_kelas_loop');
$idtanggalkelasloop = $this->request->getVar('id_tanggal_kelas_loop');
$namakelas = $this->request->getVar('nama_kls');
$waktukelas = $this->request->getVar('waktu_kls');
$statuskelas = $this->request->getVar('status_kelas');
$tanggalkelas = array(
'id_tanggal_kelas' => $this->request->getVar('id_tanggal_kelas'),
'tanggal_kls' => $this->request->getVar('tanggal_kls')
);
$this->TanggalKelasModel->save($tanggalkelas);
for ($kls = 0; $kls < count($namakelas); $kls++) {
$this->KelasModel->save([
'id_kelas' => $idkelas[$kls],
'id_tanggal_kelas' => $idtanggalkelasloop[$kls],
'nama_kls' => $namakelas[$kls],
'waktu_kls' => $waktukelas[$kls],
'status_kls' => $statuskelas[$kls]
]);
}
session()->setFlashdata('sukses', 'Agenda berhasil diunggah');
return redirect()->to('/admin/admin/create_agenda');
}
This is my "KelasModel"
class KelasModel extends Model
{
protected $table = 'kelas';
protected $primaryKey = 'id_kelas';
protected $allowedFields = [
'id_kelas', 'id_tanggal_kelas', 'nama_kls', 'waktu_kls', 'status_kls'
];
}
class TanggalKelasModel extends Model
{
protected $table = 'tanggal_kelas';
protected $primaryKey = 'id_tanggal_kelas';
protected $allowedFields = [
'id_tanggal_kelas', 'tanggal_kls'
];
}
This is my "TanggalKelasModel"
<?php
namespace App\Models;
use CodeIgniter\Model;
class TanggalKelasModel extends Model
{
protected $table = 'tanggal_kelas';
protected $primaryKey = 'id_tanggal_kelas';
protected $allowedFields = [
'id_tanggal_kelas', 'tanggal_kls'
];
}
I have tried to check the allowed fields and the column names are the same.

Simple laravel models usage

My model:
class Product extends Model
{
protected $table = 'Products';
protected $fillable = ['product_code', 'type', 'name', 'description', 'price', 'discount', 'image', 'image_alt'];
public function products()
{
return $this->hasMany('App\ProductSpecifics');
}
}
My controller code:
public function product($code)
{
$product = Product::where('product_code',$code)->get();
$productSpec = ProductSpecifics::where('product_code',$code)->get();
var_dump($product->name);
return view('pages.product', compact('product','productSpec'));
}
Error:
Property [name] does not exist on this collection instance
I tried using dd($product) and I noticed that there is a lot of information in there.
How do I extract only the attributes like name,type & etc ?
try this
dd($product->toArray());

how to get id of table in relationship to use in other table in this relation?

i have relation between Service and Services_Gallery one to many, and i want to use id of Service when i insert new image to Services_Gallery, and this is my Controller:
public function save(Request $request)
{
$this->validate($request,[
'image' => 'required|image|mimes:jpeg,jpg,png,svg|max:1024'
]);
$services_Gallery = new Services_Gallery();
$services_Gallery->image = $request->image->move('Uploads', str_random('6') . time() . $request->image->getClientOriginalName());
$services_Gallery->Service::all(id) = $request->service_id; //The problem here
$services_Gallery->save();
return back();
}
this is my Models:
class Service extends Model
{
protected $table = 'services';
protected $fillable = [
'en_main_title',
'ar_main_title',
'en_sub_title',
'ar_sub_title',
'en_content_title',
'ar_content_title',
'en_content',
'ar_content',
'priority',
];
public function gallery()
{
return $this->hasMany('App\Services_Gallery','service_id');
}
}
class Services_Gallery extends Model
{
protected $table = 'services_galleries';
protected $fillable = [
'image',
'service_id',
];
public function gallery(){
return $this->belongsTo('App\Service','service_id');
}
}
Exapmle:
$modelOfService = Service::where('param_x', $request->service_id)->first();
$id = $modelOfService->id;
Is that you need?

Eloquent: Two foreign keys in a table pointing to the same table

I have two models:
Team
Game (Played between two games)
The Game model has two foreign keys pointing to the Team model - team1_id & team2_id.
Here's the code for Team model:
class Team extends Eloquent
{
protected $table = 'team';
protected $fillable = [
'name',
'color',
'year'
];
public function games()
{
return $this->hasMany(\App\Models\Game::class);
}
}
Code for Game model:
class Game extends Eloquent
{
protected $table = 'game';
protected $casts = [
'team1_id' => 'int',
'team2_id' => 'int'
];
protected $fillable = [
'team1_id',
'team2_id',
'location',
'start_at'
];
public function team1()
{
return $this->hasOne(\App\Models\Team::class, 'team1_id');
}
public function team2()
{
return $this->hasOne(\App\Models\Team::class, 'team2_id');
}
}
I get an error saying the column could not be found.
return $this->hasMany(\App\Models\Game::class, 'team1_id');
This works, but the problem is that I want to get games depending on both team1_id and team2_id.
You had to specify the foreign key and the local key you use to reference that relation
public function localTeam()
{
return $this->belongsTo(\App\Models\Team::class, 'id', 'team1_id');
}
public function foreignTeam()
{
return $this->belongsTo(\App\Models\Team::class, 'id', 'team2_id');
}

Laravel 5.2 Model Relationships

im new to Laravel and have a relationship question.
The goal is to get all News where news.page_id = page.id AND page.pagetype_id = pagetype.id WHERE pagetype.component = news AND page.app_id = 1
class News extends Model
{
protected $table = 'news';
protected $fillable = ['page_id', 'title', 'description', 'active', 'created_at', 'updated_at'];
}
class Page extends Model
{
protected $table = 'pages';
protected $fillable = ['app_id', 'unique_id', 'pagetype_id', 'title', 'picture_url', 'short_description', 'description', 'valid_since', 'valid_until', 'extras', 'active', 'created_at', 'updated_at'];
public function pagetype() {
return $this->belongsTo('App\Models\PageType', 'pagetype_id');
}
}
class PageType extends Model
{
protected $table = 'pagetypes';
protected $fillable = ['pagetype', 'component', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->belongsToMany('App\Models\Page', 'pagetypes', 'id', 'id');
}
}
// now i need All News Items where page.pagetype_id = pagetypes.id and patchtypes.component = news
// First Attempts are
Page::whereHas('pagetype', function ($q) {
$q->where('component', 'news');
})->where(['app_id' => 1])->get();
// result is all Pages which has the proper component news.
This is what i have tried yet, but in my attempt i'll only receive the proper pages but of course not the news.
My "current" solution is to get all the pages and then loop through News::where('page_id', $myPageId). But im pretty sure its possible to get a proper relationship to get also news.
I cant do any other model since there are many different pagetypes and components aswell.
Thanks so far.
You need to add relationship function to news model.
public function pages() {
return $this->belongsTo('App\Models\Page');
}
And call it through News model.
News::with('pages')->where('app_id',1);
First off all I think that you are wrong with you PageType relation
class PageType extends Model
{
protected $table = 'pagetypes';
protected $fillable = ['pagetype', 'component', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->hasMany('App\Models\Page');
// if i understood you correctly you haven't got any pivot table
}
}
Then you should link your News and Page like so
News.php
class News extends Model
{
protected $table = 'news';
protected $fillable = ['page_id', 'title', 'description', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->belongsTo('App\Models\Page');
}
}
Page.php
class Page extends Model
{
protected $table = 'pages';
protected $fillable = ['app_id', 'unique_id', 'pagetype_id', 'title', 'picture_url', 'short_description', 'description', 'valid_since', 'valid_until', 'extras', 'active', 'created_at', 'updated_at'];
public function pagetype() {
return $this->belongsTo('App\Models\PageType');
}
public function news() {
return $this->hasMany('App\Models\News');
}
}
Then you can achieve your goal
News::whereHas('page', function($q) use($appId) {
$q->where('app_id',$appId);
})->whereHas('page.pagetype', function($q) {
$q->where('component', 'news');
})->get();

Categories