Laravel (using Livewire ) to show result from 2 different tables - laravel

I am running Laravel 5.8 and hammering my head all day against walls, to find out how to achieve this MySQL query in Laravel -> render function in my livewire component to list all available "ABKs" which include a specific text in the other table "Parts".
What I have:
2 Tables one is ABKs and the other one is PARTs < relation between them is on to many one ABK can have one part, one Part can have many ABKs. Noted the relationship in the Models, works as expected.
But if I try right now to search over both tables(to order and paginate in my livewire component) I need to have this query for example in Laravel:
SELECT * FROM `abks` LEFT JOIN parts ON abks.part_id = parts.id WHERE parts.zeichnungsnummer LIKE '%46%'
if I try this in Tinker I get the result:
$abks = ABK::where('id', 'like','%%')->with('part')->where('parts.zeichnungsnummer','like','%46%')->get();
Illuminate/Database/QueryException with message 'SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'parts.zeichnungsnummer' in
'where clause' (SQL: select * from abks where id like %% and
parts.zeichnungsnummer like %46%)',
what am I doing wrong here? Why doesn't Eloquent find this column?
just a short example what I want to achieve because my code is more complex to post here ... I think its easier to understand to post it in a little example.
a little further explanation why I need this: I have a data table which outputs all ABKs and have 2 search inputs one for the ABKs columns and one for the PARTs columns -> where the user can search for texts in ABKs and in the other one in the PARTs table. which is filtered in this way in livewire while the user types...
Thanks to all here for your great answers, and helping us a lot to learn and understand.

you missed join clause from your eloquent query:
$abks = ABK::where('id', 'like',$abksId)
->join('parts','parts.id','=','abks.part_id')
->where('parts.zeichnungsnummer','like','%46%')->get();

Related

Laravel returning Unknown column 'table.deleted_at'in 'where clause'

It seems there are lot of posts about this error, but before everything, I must say that I have use SoftDeletes; because I use it and I need it to manage trashed models.
Column 'deleted_at' also exists.
Solution like this saying to remove it does not suit in my case.
I am looking for help to keep use SoftDeletes; but making my request working properly.
Here is my query:
public function scopeWithRowNumber($query)
{
$sub = Model::selectRaw('*, #row:=#row+1 as row')
->orderBy('some_date', 'desc')->toSql();
$query->from(DB::raw("({$sub}) as sub"));
}
The sql exit gives me :
select *, #row:=#row+1 as row from `model_table`
where `model_table`.`deleted_at` is null order by `entry_date` desc
How to fix it?
I finally use this:
withoutGlobalScope('Illuminate\Database\Eloquent\SoftDeletingScope')
on my queries to avoid checking deleted_at column.
The issue is relative to nested queries and seems "normal". In my case, this helps me to fix/avoid error:
> Unknown column 'deleted_at' or column not found.
Maybe it will help someone else.
Also for ranking, I was inspired by this post. But I have to edit my query a little bit because of more conditions with dynamic parameters I added. But this is another subject.

Get unique value from table Laravel

I want to get all rows that have one unique column. The problem with my code is that it works only when I select just that one column, but in the end I need to have multiple columns.
$values= Model::select('id','value_first','gender_first','value_second','gender_second')->groupBy('value_first')->get();
Here is Solution of Your Problem
$values= Model::select('id','value_first','gender_first','value_second','gender_second')->distinct('value_first')->get();
As per Laravel Documentation you can use distinct method for the same
The distinct method allows you to force the query to return distinct
results for e.g
$values= Model::select('id','value_first','gender_first','value_second','gender_second')->distinct('value_first')->get();
Reference: Laravel-> Database: Query Builder -> Selects

Why does this DAX relationship between tables not aggregate as expected?

A very basic question about relationships between tables:
I have made a test with two tables ("Dates" and "Facts") and have connected them via an ID field:
When I try to count and group the count by Dates[YearMonth], I am only getting the expected results for the Facts[BirthID] column, and not for the Facts[StartID] or Facts[EndID]. So I am only getting the expected results from the column that is the relationship to the Dates table (where the YearMonth column is that I am trying to group by. This screenshot shows the tables, expected results and actual results:
This is probably very simple, but I can't figure out why it is not aggregating the data "correctly" by YearMonth.
Could someone explain to me what I am doing wrong?
We get same count for Facts[StartID] or Facts[EndID] because the join is on BirthID. If we change the join to use Facts[StartID] or Facts[EndID] we get the expected results as you have shown.
We can also create inactive relationship and activate the relationship with DAX USERELATIONSHIP function. Then we get the expected results.
USERELATIONSHIP

Angular Data tables multiple row section headers

I have a table that is already listed in ascending desired order with two distinct sections and I want to add headers for each section but I'm not quite sure how to do so. I am using the directive Angular datatables and would like to have the end result have row titles like the "Status:New" and "Status:Open" in the example image below.
After much research, currently there is no supported way to fix rows in the middle of the specific table I'm working with.
Add something like this after your initial code for your table. Assuming you're using 2 tables.
var table1 = $("#your_top_table").DataTable({});
$(table.table().header()).append('<tr><td>Status: New</td></tr>');
var table2 = $("#your_bottom_table").DataTable({});
$(table2.table().header()).append('<tr><td>Status: Open</td></tr>');

Laravel - Really struggling to understand eloquent

I'm fairly new to Laravel having come over from Codeigniter and for the most part I really like it, but I really can't get my head around Eloquent.
If I want to do a simple query like this:
SELECT * FROM site INNER JOIN tweeter ON tweeter.id = site.tweeter_id
I try doing something like this (with a "belongs to"):
$site = Site::with('tweeter')->find($site_id);
But now I have two queries and an IN() which isn't really needed, like so:
SELECT * FROM `site` WHERE `id` = '12' LIMIT 1
SELECT * FROM `tweeter` WHERE `id` IN ('3')
So I try and force a join like so:
$site = Site::join('tweeter', 'tweeter.id', '=', 'site.tweeter_id')->find($site_id);
And now I get an error like so:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous
SQL: SELECT * FROM `site` INNER JOIN `tweeter` ON `tweeter`.`id` = `site.tweeter_id` WHERE `id` = ? LIMIT 1
Bindings: array (
0 => 12,
)
It's obvious where the error is, the where needs to use something like "site.id = ?". But I can't see anyway to make this happen?
So i'm just stuck going back to fluent and using:
DB::table('site')->join('tweeter', 'tweeter.id', '=', 'site.tweeter_id')->where('site.id','=',$site_id)->first()
I guess it's not a massive problem. I would just really like to understand eloquent. I can't help but feel that i'm getting it massively wrong and misunderstanding how it works. Am I missing something? Or does it really have to be used in a very specific way?
I guess my real question is: Is there anyway to make the query I want to make using Eloquent?
I actually find this behaviour advantageous. Consider this (I'll modify your example). So we have many sites and each has many tweeters. Each site has a lot of info in the DB: many columns, some of them text columns with lots of text / data.
You do the query your way:
SELECT * FROM site INNER JOIN tweeter ON tweeter.id = site.tweeter_id
There are two downsides:
You get lots of redundant data. Each row you get for a tweeter of the same site will have the same site data that you only need once so the communication between PHP and your DB takes longer.
How do you do foreach (tweeter_of_this_site)? I'm guessing you display all the sites in some kind of list and then inside each site you display all of it's tweeters. You'll have to program some custom logic to do that.
Using the ORM approach solves both these issues: it only gets the site data once and it allows you to do this:
foreach ($sites as $site) {
foreach($site->tweeters as $tweeter) {}
}
What I'm also saying is: don't fight it! I used to be the one that said: why would I ever use an ORM, I can code my own SQL, thank you. Now I'm using it in Laravel and it's great!
You can always think of Eloquent as an extension of Fluent.
The problem you're running into is caused by the find() command. It uses id without a table name, which becomes ambiguous.
It's a documented issue: https://github.com/laravel/laravel/issues/1050
To create the command you are seeking, you can do this:
$site = Site::join('tweeter', 'tweeter.id', '=', 'site.tweeter_id')->where('site.id', '=', $site_id)->first($fields);
Of course, your syntax with join()->find() is correct once that issue fix is adopted.

Resources