Problem saving data into Polymorphic relationship laravel - php

I have some doubts on polymorphic relationship.
I have the schema attached where document can be connected to sectors if 'senderable_type' is Sector or, to addresses if is Address.
Base on value get from a form, I know if it is connected to a Sector or to an Address, getting its ID.
But...how to do this? Can you help me please?
Each document can be linked to one sector or to one address. Is it possible to use Polymorphic for this use?
These are my relationships on models:
//Document.php
public function documentable()
{
return $this->morphTo();
}
//Sector.php
public function documents()
{
return $this->morphMany(Document::class, 'senderable');
}
//Address.php
public function documents()
{
return $this->morphMany(Document::class, 'senderable');
}
And this is the code of my store function in my controller:
if (is_null($request->get('sender_id'))) {
$type = "App\Sector";
$sender_id = $request->get("sector_id");
} else {
$type = "App\Address";
$sender_id = $request->get("sender_id");
}
$documento = Document::create(
[
'company_id' => $request->get("company_id") ?? Auth::user()->company_id,
'date' => Carbon::createFromFormat("d/m/Y", $request->get("date")),
'type' => $request->get("origin"),
'subject' => $request->get("subject"),
'senderable_type' => $type,
'senderable_id' => $sender_id,
'protocol_number' => '0',
'protocol_date' => Carbon::now(),
'is_reserved' => false,
'created_user_id' => Auth::id(),
]
);
Actually I check if it is related to a Sector or to an Address and manually save in the DB. I don't know if it is the best way...

Related

how to use laravel eloquent to get and display data from other tables

I was using these codes in my controller to get all the data from my 2 tables and it works fine
$All = Customers::with('order')->paginate(10);
return response()->json([
'code' => 0,
'success' => true,
'data' => $All
], 200);
Here is how I define the relationship between these 2 tables
class Customers extends Model
{
public function order()
{
return $this->hasMany(Orders::class, 'customer_id', 'id');
}
}
class Orders extends Model
{
public function customers()
{
return $this->belongsTo(Customers::class, 'customer_id', 'id');
}
}
Now my desire output is to hide the order id, order timestamps and change the customer_id to customer's name (the customer's name is not in my orders db table).
I'm using 'data' => DataResource::collection($All) in my controller and this is my DataResource
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'order' => $this->order
];
}
and of course the output is same with the image above.
My database structure:
orders table:
customer table:
Can anyone help me with that?
The answer is simple and basically a copy of the official documentation. You simply need to wrap your orders in an OrderResource as well.
// DataResource
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'order' => OrderResource::collection($this->order)
];
}
// OrderResource
public function toArray($request)
{
return [
'items' => $this->items,
'quantity' => $this->quantity
];
}
I don't really understand why you would want to include the customer_name in your orders when it is already present on the customers object one hierarchy above. But if you really want to add it, you should be able to do so with: 'customer_name' => $this->customers->name.
As a side note: you really should be more consistent with your naming. Why is the resource called DataResource when it is about Customers? Why is your model called Customers in plural form rather than Customer in singular, which is the convention (and more logical if you consider that one model represents one customer). Why is your belongsTo relation called customers() in plural when it returns one customer, while your hasMany relation is called order whereas it returns one or more orders?

Laravel seeder not working

Can anyone see what seems to be the problem with my seeder?
public function run()
{
$faker = Faker\Factory::create();
$limit = 30;
$userId = App\User::all()->lists('id')->toArray();
$status = App\OrderStatus::all()->lists('id')->toArray();
for ($i = 0; $i < $limit; $i++) {
$chosenUserId = $faker->randomElement($userId);
$user = App\User::find($chosenUserId);
DB::table('orders')->insert([
'created_at' => $faker->date('Y-m-d'),
'user_id' => $chosenUserId,
'status_id' => $faker->randomElement($status),
'draft' => false,
'address_id' => $user->addresses->first()->id
]);
}
}
I keep getting trying to get property of non-object error, and I suppose it's because of the last line where I'm attaching address_id.
When I take a look at the DB what was created until that point, users and addresses are created fine, and each user has an address assigned to him.
In user model i have:
public function addresses()
{
return $this->hasMany('App\Address');
}
Here:
addresses -> addresses()
Since your User model have a function to define the relationship with address model, you should call it as a function not as object attributes:
DB::table('orders')->insert([
'created_at' => $faker->date('Y-m-d'),
'user_id' => $chosenUserId,
'status_id' => $faker->randomElement($status),
'draft' => false,
'address_id' => $user->addresses()->first()->id
]);

Yii Framework - ActiveRecord not returning data of join table

Yii Framework ist really great, but I encountered a problem when using Active Record for querying data from MySQL database.
When I join 2 tables ('building' and 'building_info') in my Function "get" in model Building, there will be no data returned from my second table. If I execute the same query with Query Class, rows from both table will be returned. With Active Record I get only data from table 'building'.
Model Building:
...
// Setting Relation
public function getBuildingInfos()
{
return $this->hasMany(BuildingInfo::className(), ['BuildingID' => 'ID']);
}
// Get all buildings
public function get() {
$building = Building::find()
->joinWith('buildingInfos')
->where(['building_info.langID' => 1])
->all();
return $building;
}
// Attributes
public function attributeLabels()
{
return [
'ID' => 'ID',
'NameBreak' => 'Name Break',
'Tileset' => 'Tileset',
'TilesetPosition' => 'Tileset Position',
...
]
}
...
Model BuildingInfo:
...
public function attributeLabels()
{
return [
'buInfoID' => 'Bu Info ID',
'BuildingID' => 'Building ID',
'langID' => 'Lang ID',
'Name' => 'Name',
'ShortDesc' => 'Short Desc',
'ShortDescDisabled' => 'Short Desc Disabled',
];
}
public function getBuilding()
{
return $this->hasOne(Building::className(), ['ID' => 'BuildingID']);
}
...
Do you know how to solve this problem?
Thanks
Kevin
Ciao Kevin :) are you using yii1 or yii2?
In 'getBuildingInfos', the table is linked by BuidingID, in your get function, you are linking it by building_info.langID.. Have you already verified that your join works in sql?

Eloquent automatically selects unwanted columns upon eager-loading model relationship

I am converting an internal API from HTML (back-end) processing to JSON (using Knockout.js) processing on the client-side to load a bunch of entities (vehicles, in my case).
The thing is our database stores sensitive information that cannot be revelead in the API since someone could simply reverse engineer the request and gather them.
Therefore I am trying to select specifically for every relationship eager-load the columns I wish to publish in the API, however I am having issues at loading a model relationship because it seems like Eloquent automatically loads every column of the parent model whenever a relationship model is eager loaded.
Sounds like a mindfuck, I am aware, so I'll try to be more comprehensive.
Our database stores many Contract, and each of them has assigned a Vehicle.
A Contract has assigned an User.
A Vehicle has assigned many Photo.
So here's the current code structure:
class Contract
{
public function user()
{
return $this->belongsTo('User');
}
public function vehicle()
{
return $this->belongsTo('Vehicle');
}
}
class Vehicle
{
public function photos()
{
return $this->hasMany('Photo', 'vehicle_id');
}
}
class Photo
{
[...]
}
Since I need to eager load every single relationship listed above and for each relationship a specific amount of columns, I need to do the following:
[...]
$query = Contract::join('vehicles as vehicle', 'vehicle.id', '=', 'contract.vehicle_id')->select([
'contract.id',
'contract.price_current',
'contract.vehicle_id',
'contract.user_id',
'contract.office_id'
]);
[...]
$query = $query->with(['vehicle' => function ($query) {
$query->select([
'id',
'trademark',
'model',
'registration',
'fuel',
'kilometers',
'horsepower',
'cc',
'owners_amount',
'date_last_revision',
'date_bollo_expiration',
'bollo_price',
'kilometers_last_tagliando'
]);
}]);
$query = $query->with(['vehicle.photos' => function ($query) {
$query->select([
'id',
'vehicle_id',
'order',
'paths'
])->where('order', '<=', 0);
}]);
$query = $query->with(['user' => function ($query) {
$query->select([
'id',
'firstname',
'lastname',
'phone'
]);
}]);
$query = $query->with(['office' => function ($query) {
$query->select([
'id',
'name'
]);
}]);
[...]
return $this->response->json([
'error' => false,
'vehicles' => $vehicles->getItems(),
'pagination' => [
'currentPage' => (integer) $vehicles->getCurrentPage(),
'lastPage' => (integer) $vehicles->getLastPage(),
'perPage' => (integer) $vehicles->getPerPage(),
'total' => (integer) $vehicles->getTotal(),
'from' => (integer) $vehicles->getFrom(),
'to' => (integer) $vehicles->getTo(),
'count' => (integer) $vehicles->count()
],
'banner' => rand(0, 2),
'filters' => (count($input) > 4),
'filtersHelpText' => generateSearchString($input)
]);
The issue is: if I do not eager load vehicle.photos relationship, columns are loaded properly. Otherwise, every single column of Vehicle's model is loaded.
Here's some pictures so you can understand:
Note: some information have been removed from the pictures since they are sensitive information.
You can set a hidden property on your models which is an array of column names you want to hide from being output.
protected $hidden = ['password'];

Laravel 4 - Insert through hasMany relationship

Here is my model relationship...
class User extends Eloquent {
public function loginLog(){
return $this->hasMany('LoginLog');
}
}
class LoginLog extends Eloquent {
public function user(){
return $this->belongsTo('User');
}
}
When I insert data into the login_logs table in my database all the data is input correctly but it does not insert the id of the user into user_id (laravel expects this).
Here is how I am inserting into login_logs.
$user->loginLog()->insert(array(
'user_id' => $user->id, //I could put it here, but then what is the point in a relationship?
'email' => $user->email,
'ip_address' => Request::getClientIp(),
'country_code' => $country_code,
'status' => $status,
'created_at' => Helper::dateTimeNow()
));
You have to attach the user.
Its here in the docs
http://laravel.com/docs/eloquent#inserting-related-models
Update:
On rereading your question I think you want to find the user by their id first as you are doing $user->loginLog()->insert not $loginLog->insert
Try chaining it so:
$user::find($theIDYouWant)->loginLog()->insert

Categories